public static bool Export(ChartControl _chart) { SaveFileDialog _sf = new SaveFileDialog(); _sf.Filter = "JPG文件|*.jpg|Excle文件|*.xls|HTML文件|*.mht|BMP文件|*.bmp|PNG文件|*.png"; _sf.FilterIndex = 1; string _fname = ""; while (_fname == "") { if (_sf.ShowDialog() == DialogResult.OK) { _fname = _sf.FileName; if (_fname != "") { switch (_sf.FilterIndex) { case 1: _chart.ExportToImage(_fname, ImageFormat.Jpeg); break; case 2: _chart.ExportToXls(_fname); break; case 3: _chart.ExportToMht(_fname); break; case 4: _chart.ExportToImage(_fname, ImageFormat.Bmp); break; case 5: _chart.ExportToImage(_fname, ImageFormat.Png); break; } return(true); } else { XtraMessageBox.Show("请输入导出文件名!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { return(false); } } return(false); }
public static void DoTest() { ChartControl chart = new ChartControl(); chart.Width = 900; // Specify data members to bind the chart's series template. chart.SeriesDataMember = "Type"; chart.SeriesTemplate.Label.Visible = false; chart.SeriesTemplate.ArgumentDataMember = "Hour"; chart.SeriesTemplate.ArgumentScaleType = ScaleType.DateTime; chart.SeriesTemplate.ValueDataMembers.AddRange(new string[] { "Value" }); XYDiagram diagram = chart.Diagram as XYDiagram; diagram.AxisX.DateTimeGridAlignment = DateTimeMeasurementUnit.Hour; diagram.AxisX.DateTimeMeasureUnit = DateTimeMeasurementUnit.Second; diagram.AxisX.GridSpacing = 1; diagram.AxisX.DateTimeOptions.Format = DateTimeFormat.Custom; diagram.AxisX.DateTimeOptions.FormatString = "HH:mm"; // Specify the template's series view. chart.SeriesTemplate.View = new SideBySideBarSeriesView(); // Specify the template's name prefix. chart.SeriesNameTemplate.BeginText = ""; // Generate a data table and bind the chart to it. DataView dv = CreateChartData().DefaultView; dv.Sort = "Hour asc"; chart.DataSource = dv; chart.ExportToImage("f:\\1.jpg", ImageFormat.Jpeg); }
/// <summary> /// 图标控件导出Excel(Image,jpg) /// </summary> /// <param name="chart"></param> public static void ChartExportImage(ChartControl chart) { var saveFileDialog = new SaveFileDialog { FileName = DateTime.Now.ToString(BaseSystemInfo.DateFormat) + "打印数据", Title = @"导出JPG", Filter = @"图片文件(*.jpg)|*.jpg", OverwritePrompt = false }; //已存在文件是否覆盖提示 var dialogResult = saveFileDialog.ShowDialog(); if (dialogResult != DialogResult.OK) { return; } while (System.IO.File.Exists(saveFileDialog.FileName) && XtraMessageBox.Show("该文件名已存在,是否覆盖?", AppMessage.MSG0000, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { if (dialogResult != DialogResult.Yes) { return; } } if (string.IsNullOrEmpty(saveFileDialog.FileName)) { return; } try { chart.ExportToImage(saveFileDialog.FileName, ImageFormat.Jpeg); OpenFile(saveFileDialog.FileName); } catch (Exception ex) { XtraMessageBox.Show(ex.Message.Contains("正由另一进程使用") ? "数据导出失败!文件正由另一个程序占用!" : ex.Message, AppMessage.MSG0000); } }
private void barMgrAlarmHistoryChart_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { string fileName = GetFilePath(e.Item.Caption, GetFilter(e.Item.Caption)); if ("" == fileName) { return; } switch (e.Item.Caption) { case "Export to Excel": { ctcAlarmHistory.ExportToXlsx(fileName); } break; case "Export to IMG": { ChartControl chart = (ChartControl)ctcAlarmHistory.Clone(); chart.Size = new Size(1200, 1200); chart.ExportToImage(fileName, ImageFormat.Jpeg); chart.Dispose(); } break; case "Export to PDF": { ctcAlarmHistory.ExportToXlsx(fileName); } break; } }
private void RibbonForm1_Load(object sender, EventArgs e) { // Label label1 = new Label(); label1.Text = Common.Dominant + "漏洞扫描报告"; int w = label1.Width; label1.Location = new Point(300 - w / 2, 13); label1.Visible = true; xtraScrollableControl1.Controls.Add(label1); ChartControl pieChart = new ChartControl(); Series series1 = new Series("漏洞分布", ViewType.Pie); foreach (var item in Common.playload) { i++; } if (i <= 5) { strlab2 = "得分为:" + (100 - i * 10); } else if (i > 5 & i <= 10) { strlab2 = "得分为:" + (50 - i * 3); } else { strlab2 = "得分为:20"; } label2.Text = strlab2; foreach (var item in Common.poc) { j++; } series1.Points.Add(new SeriesPoint("不存在XSS占比", j * 1.0 / (i + j))); series1.Points.Add(new SeriesPoint("存在XSS占比", 1.0 - (j / (i + j)))); series1.Label.TextPattern = "{A}: {VP:p0}"; pieChart.Series.Add(series1); pieChart.Location = new Point(0, 67); pieChart.Size = new System.Drawing.Size(600, 600); xtraScrollableControl1.Controls.Add(pieChart); if (pieChart.IsPrintingAvailable) //是否能被打印或输出 { path = dd + "\\" + Common.Dominant.Replace(".", "1") + ".png"; pieChart.ExportToImage(path, ImageFormat.Png); } RichTextBox rtb = new RichTextBox(); //ListBox lb = new ListBox(); rtb.Size = new System.Drawing.Size(600, 100); rtb.Location = new Point(0, 690); rtb.AppendText("playload为:\n"); foreach (var item in Common.result) { rtb.AppendText(item + "\n"); } xtraScrollableControl1.Controls.Add(rtb); richTextBox1.Location = new Point(0, 800); }
private static void CreateChart(ArrayList allNumbers, string name) { var numberOccurrence = allNumbers.ToArray().GroupBy(x => x) .ToDictionary(g => g.Key, g => g.Count()); var dt = new DataTable("Lotto"); dt.Columns.Add("Number", typeof(int)); dt.Columns.Add("Occurence", typeof(int)); var chart = new ChartControl(); chart.Padding.All = 0; chart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False; chart.Width = 900; chart.Height = 600; var series = new Series("Series", ViewType.Bar) { ValueScaleType = ScaleType.Numerical, ArgumentScaleType = ScaleType.Numerical }; for (var i = 1; i < 35; i++) { dt.Rows.Add(i, numberOccurrence.FirstOrDefault(a => Convert.ToInt32(a.Key) == i).Value); } series.DataSource = dt; series.ArgumentDataMember = dt.Columns[0].ColumnName; series.ValueDataMembers.AddRange(dt.Columns[1].ColumnName); chart.Series.Add(series); if (true) { ((SideBySideBarSeriesView)series.View).BarWidth = 1; var diagram = (XYDiagram)chart.Diagram; diagram.Margins.All = 0; // Define the whole range for the X-axis. diagram.AxisX.Tickmarks.Visible = false; diagram.AxisX.Tickmarks.MinorVisible = true; diagram.AxisX.GridLines.Visible = false; diagram.AxisX.GridLines.MinorVisible = true; diagram.AxisX.MinorCount = 1; diagram.AxisX.Label.MaxLineCount = 1; diagram.AxisX.WholeRange.Auto = false; diagram.AxisX.WholeRange.SetMinMaxValues(1, 34); diagram.AxisX.VisualRange.Auto = false; diagram.AxisX.VisualRange.SetMinMaxValues(1, 34); diagram.AxisX.VisualRange.AutoSideMargins = false; diagram.AxisX.WholeRange.SideMarginsValue = 0.5; diagram.AxisY.WholeRange.Auto = false; } chart.ExportToImage(SavePath + name + ".png", ImageFormat.Png); }
public static Image ChartToImage(ChartControl chart) { Image image = null; // Create an image of the chart. using (MemoryStream s = new MemoryStream()) { chart.ExportToImage(s, ImageFormat.Png); image = Image.FromStream(s); } return(image); }
static void ExportTo(string title, string filter, string exportFormat, ImageFormat format, bool checkPrinterAvailable) { ChartControl chart = PrepeareForPrintOrExport(checkPrinterAvailable); if (chart == null) { return; } string fileName = ShowSaveFileDialog(title, filter); if (fileName != "") { Cursor currentCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; switch (exportFormat) { case "HTML": chart.ExportToHtml(fileName); break; case "MHT": chart.ExportToMht(fileName); break; case "PDF": PrintSizeMode sizeMode = chart.OptionsPrint.SizeMode; chart.OptionsPrint.SizeMode = PrintSizeMode.Zoom; try { chart.ExportToPdf(fileName); } finally { chart.OptionsPrint.SizeMode = sizeMode; } break; case "XLS": chart.ExportToXls(fileName); break; case "IMAGE": chart.ExportToImage(fileName, format); break; } Cursor.Current = currentCursor; OpenFile(fileName); } }
public static Image csGetChartImage(this ChartControl chart, ImageFormat format) { // Create an image. Image image = null; // Create an image of the chart. using (MemoryStream s = new MemoryStream()) { chart.ExportToImage(s, format); image = Image.FromStream(s); } // Return the image. return(image); }
protected override Image DoCreateChartImage() { using (var chart = new ChartControl()) { var series1 = new Series("Series 1", ViewType.Line); series1.Points.AddRange(Parameters.SeriaData.Select(p => new SeriesPoint(p.Key,p.Value)).ToArray()); chart.Series.Add(series1); chart.Width = Parameters.ChartWidth; chart.Height = Parameters.ChartHeight; using (var stream = new MemoryStream()) { chart.ExportToImage(stream, ImageFormat.Png); return Image.FromStream(stream); } } }
private bool SaveChartToFile(ChartControl chartControl) { if (chartControl == null) { throw new ArgumentNullException("chartControl"); } bool result = false; try { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "bmp-файл (*.bmp)|*.bmp|jpeg-файл (*.jpeg)|*.jpeg|png-файл (*.png)|*.png"; if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { var fi = new System.IO.FileInfo(sfd.FileName); ImageFormat format = null; switch (fi.Extension) { case ".bmp": format = ImageFormat.Bmp; break; case ".jpeg": format = ImageFormat.Jpeg; break; case ".png": format = ImageFormat.Png; break; } if (format != null) { chartControl.ExportToImage(fi.FullName, format); result = true; } } } catch (Exception exc) { result = false; } return(result); }
public static string csSaveChartImageToFile(this ChartControl c, string path, string chartName = null) { if (string.IsNullOrEmpty(chartName)) { ChartElement[] t = c.Titles.ToArray(); if (t.Length > 0) { foreach (ChartElement chartElement in t) { chartName += (chartElement + " "); } } } chartName = chartName.Replace("\r\n", " ").Replace("/", "-").Replace(":", "_").Trim(); // strip out the html int loc = chartName.IndexOf('<'); while (loc > -1) { // find closing angle bracket int floc = chartName.IndexOf('>'); if (floc > loc) { chartName = chartName.Substring(0, loc) + " " + chartName.Substring(floc + 1); loc = chartName.IndexOf('<'); } else { break; } } chartName = chartName.Replace('<', '-').Replace('>', '-'); var temp = MyLib.GetSaveFileName(path , "png" , "png" , "Save Chart Image" , chartName); if (string.IsNullOrEmpty(temp)) { return(path); } c.ExportToImage(temp, ImageFormat.Png); return(Path.GetDirectoryName(temp)); }
public TestForm() { InitializeComponent(); List<TypeACopy> lst = new List<TypeACopy>() { new TypeACopy() {TypeName = "Tại thư viện", NoC = 66}, new TypeACopy() {TypeName = "Đã được mượn", NoC = 3}, new TypeACopy() {TypeName = "Đã mất", NoC = 20} }; Series serie1 = new Series("Số lượng sách trong thư viện", ViewType.Pie); serie1.ArgumentDataMember = "TypeName"; serie1.ValueDataMembers[0] = "NoC"; //serie1.LegendPointOptions.ValueNumericOptions.Format = NumericFormat.Percent; serie1.LegendPointOptions.PointView = PointView.Argument; serie1.PointOptions.ValueNumericOptions.Format = NumericFormat.FixedPoint; ((PiePointOptions) serie1.PointOptions).PercentOptions.ValueAsPercent = false; ChartControl c = new ChartControl(); c.Series.Add(serie1); c.DataSource = lst; c.ExportToImage("D:\\Demo.jpg", ImageFormat.Jpeg); GridControl gc = new GridControl(); DataTable dt = new DataTable(); SqlDataReader reader = LIB.Common.ConnectionManager.GetCommand("ReportOfRentalByUserId", new Dictionary<string, SqlDbType>() { {"@UserId", SqlDbType.NVarChar}}, new List<object>() {"admin"}).ExecuteReader(); dt.Load(reader); gc.DataSource = dt; GridView view = new GridView(); view.GridControl = gc; gridControl1.DataSource = dt; gridControl1.ExportToPdf("D:\\Demo.pdf"); //cctlTestChart.Series.Add(serie1); //cctlTestChart.DataSource = lst; }
public static void XuatHinhAnh(ChartControl chartControl) { var folder = new FolderBrowserDialog(); if (folder.ShowDialog() != DialogResult.OK) { return; } var fileName = string.Concat(Guid.NewGuid().ToString(), ".jpg"); string exportFilePath = string.Concat(folder.SelectedPath, "\\", Guid.NewGuid().ToString(), "_", DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss"), ".jpg"); //string exportFilePath = string.Concat(Application.StartupPath, @"\", fileName); ImageFormat image = ImageFormat.Jpeg; chartControl.ExportToImage(exportFilePath, image); if (File.Exists(exportFilePath)) { XtraMessageBox.Show("Xuất hình ảnh thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); Process.Start(folder.SelectedPath); } }
/// <summary> /// Chart From 00:00:00 to 23:59:59 /// </summary> void Chart2Image(string SensorID, DateTime Now) { ChartControl lineChart = new ChartControl(); lineChart.Size = new Size(1000, 500); Series series1 = new Series("Temperature (C)", ViewType.Line); Series series2 = new Series("Humidity (%)", ViewType.Line); DataTable dt = _SQLServices.GetDataForChart(SensorID, Now.Date, Now); foreach (DataRow dr in dt.Rows) { series1.Points.Add(new SeriesPoint(Convert.ToDateTime(dr["Time"]), Convert.ToDouble(dr["Temperature"]))); series2.Points.Add(new SeriesPoint(Convert.ToDateTime(dr["Time"]), Convert.ToDouble(dr["Humidity"]))); } lineChart.Series.Add(series2); lineChart.Series.Add(series1); series1.ArgumentScaleType = ScaleType.DateTime; XYDiagram diagram = (XYDiagram)lineChart.Diagram; diagram.AxisX.DateTimeMeasureUnit = DateTimeMeasurementUnit.Minute; diagram.AxisX.DateTimeOptions.Format = DateTimeFormat.ShortTime; //((LineSeriesView)series1.View).LineMarkerOptions.Kind = MarkerKind.Circle; //((LineSeriesView)series1.View).LineMarkerOptions.Visible = false; ((LineSeriesView)series1.View).LineStyle.DashStyle = DashStyle.Solid; ((LineSeriesView)series1.View).Color = Color.Red; ((LineSeriesView)series2.View).LineStyle.DashStyle = DashStyle.Solid; ((LineSeriesView)series2.View).Color = Color.Blue; lineChart.Titles.Add(new ChartTitle()); lineChart.Titles[0].Text = "Sensor Data Today: " + DateTime.Now.ToString("dd-MM-yyyy"); lineChart.Dock = DockStyle.Fill; lineChart.ExportToImage(string.Format(@"C:\inetpub\wwwroot\SENSOR_Image\Chart_{0}_{1}.jpg", SensorID, Now.ToString("yyyyMMddHHmmss")), System.Drawing.Imaging.ImageFormat.Jpeg); }
/// <summary> /// Chart From Last 1 Hour /// </summary> void Chart2ImageDetails(string SensorID, string PathName) { ChartControl lineChart = new ChartControl(); lineChart.Size = new Size(1000, 500); Series series1 = new Series("Temperature (C)", ViewType.Line); Series series2 = new Series("Humidity (%)", ViewType.Line); DataTable dt = _SQLServices.GetDataForChart(SensorID, DateTime.Now.AddHours(-1), DateTime.Now); foreach (DataRow dr in dt.Rows) { series1.Points.Add(new SeriesPoint(Convert.ToDateTime(dr["Time"]), Convert.ToDouble(dr["Temperature"]))); series2.Points.Add(new SeriesPoint(Convert.ToDateTime(dr["Time"]), Convert.ToDouble(dr["Humidity"]))); } lineChart.Series.Add(series2); lineChart.Series.Add(series1); series1.ArgumentScaleType = ScaleType.DateTime; XYDiagram diagram = (XYDiagram)lineChart.Diagram; diagram.AxisX.DateTimeMeasureUnit = DateTimeMeasurementUnit.Minute; diagram.AxisX.DateTimeOptions.Format = DateTimeFormat.ShortTime; //((LineSeriesView)series1.View).LineMarkerOptions.Kind = MarkerKind.Circle; ((LineSeriesView)series1.View).LineStyle.DashStyle = DashStyle.Solid; ((LineSeriesView)series2.View).LineStyle.DashStyle = DashStyle.Solid; lineChart.Titles.Add(new ChartTitle()); lineChart.Titles[0].Text = string.Format("Details From {0} To {1} {2} ", DateTime.Now.AddHours(-1).ToString("HH:mm:ss"), DateTime.Now.ToString("HH:mm:ss"), DateTime.Now.ToString("dd-MM-yyyy")); // Add the chart to the form. lineChart.Dock = DockStyle.Fill; lineChart.ExportToImage(string.Format(@"C:\inetpub\wwwroot\SENSOR_Image\ChartDetails_{0}_{1}.jpg", SensorID, PathName), System.Drawing.Imaging.ImageFormat.Jpeg); }
private void btnExport_Click(object sender, EventArgs e) { try { if (dt == null || dt.Rows.Count == 0) { MessageDxUtil.ShowTips("没有数据需要导出!"); return; } string saveDocFile = FileDialogHelper.SaveExcel(string.Format("{0}.xls", ReportTitle), "C:\\"); if (!string.IsNullOrEmpty(saveDocFile)) { Workbook workbook = new Workbook(); Worksheet worksheet = workbook.Worksheets[0]; worksheet.PageSetup.Orientation = PageOrientationType.Landscape; //横向打印 worksheet.PageSetup.Zoom = 100; //以100%的缩放模式打开 worksheet.PageSetup.PaperSize = PaperSizeType.PaperA4; #region 表头及说明信息 Range range; Cell cell; string content; int colSpan = 3; range = worksheet.Cells.CreateRange(0, 0, 1, colSpan); range.Merge(); range.RowHeight = 20; range.SetStyle(CreateTitleStyle(workbook)); cell = range[0, 0]; cell.PutValue(ReportTitle); range = worksheet.Cells.CreateRange(1, 0, 1, colSpan); range.Merge(); range.RowHeight = 15; cell = range[0, 0]; content = string.Format("所选查询条件内,总计有{0}个统计项,详细列表如下:", dt.Rows.Count); cell.PutValue(content); #endregion #region 生成报表头部表格 Style headStyle = CreateStyle(workbook, true); Style normalStyle = CreateStyle(workbook, false); int startRow = 2; int startCol = 0; range = worksheet.Cells.CreateRange(startRow, 0, 2, 1); range.Merge(); range.SetStyle(headStyle); cell = range[0, 0]; cell.PutValue("序号"); cell.SetStyle(headStyle); range = worksheet.Cells.CreateRange(startRow, 1, 2, 1); range.Merge(); range.SetStyle(headStyle); range.ColumnWidth = 40; cell = range[0, 0]; cell.PutValue("统计项目"); cell.SetStyle(headStyle); range = worksheet.Cells.CreateRange(startRow, 2, 2, 1); range.Merge(); range.SetStyle(headStyle); range.ColumnWidth = 40; cell = range[0, 0]; cell.PutValue("统计值"); cell.SetStyle(headStyle); #endregion //写入数据到Excel startRow = startRow + 2; for (int i = 0; i < dt.Rows.Count; i++) { //添加序号 cell = worksheet.Cells[startRow, 0]; cell.PutValue(i + 1); cell.SetStyle(normalStyle); startCol = 1; for (int j = 0; j < dt.Columns.Count; j++) { DataRow dr = dt.Rows[i]; cell = worksheet.Cells[startRow, startCol]; cell.PutValue(dr[j]); cell.SetStyle(normalStyle); startCol++; } startRow++; } //写入图注 startRow += 1;//跳过1行 range = worksheet.Cells.CreateRange(startRow++, 0, 1, colSpan); range.Merge(); range.RowHeight = 15; cell = range[0, 0]; cell.PutValue("以饼图展示如下:"); //插入图片到Excel里面 using (MemoryStream stream = new MemoryStream()) { stream.Position = 0; ChartControl chart = (ChartControl)chartPie.Clone(); chart.Size = new Size(600, 400); chart.ExportToImage(stream, ImageFormat.Jpeg); worksheet.Pictures.Add(startRow, 0, stream); } //写入图注 startRow += 25;//跳过20行 range = worksheet.Cells.CreateRange(startRow++, 0, 1, colSpan); range.Merge(); range.RowHeight = 15; cell = range[0, 0]; cell.PutValue("以柱状图展示如下:"); //插入图片到Excel里面 using (MemoryStream stream = new MemoryStream()) { stream.Position = 0; ChartControl chart = (ChartControl)chartBar.Clone(); chart.Size = new Size(800, 300); chart.ExportToImage(stream, ImageFormat.Jpeg); worksheet.Pictures.Add(startRow, 0, stream); } workbook.Save(saveDocFile); if (MessageUtil.ShowYesNoAndTips("保存成功,是否打开文件?") == System.Windows.Forms.DialogResult.Yes) { System.Diagnostics.Process.Start(saveDocFile); } } } catch (Exception ex) { LogTextHelper.Error(ex); MessageUtil.ShowError(ex.Message); return; } }
public Stream CreateChart() { using (ChartControl chart = new ChartControl()) { if (_Width.HasValue) { chart.Width = _Width.Value; } if (_Height.HasValue) { chart.Height = _Height.Value; } int undefined = 1; MemoryStream stream = new MemoryStream(); try { Series series = new Series("Chart", _ViewType); try { if (series.Label is DevExpress.XtraCharts.PieSeriesLabel) { ((DevExpress.XtraCharts.PieSeriesLabel)series.Label).Position = PieSeriesLabelPosition.Inside; } if (_ViewType == ViewType.Pie) { series.Label.PointOptions.ValueNumericOptions.Format = DevExpress.XtraCharts.NumericFormat.Percent; } if (_Data == null || _Data.Count == 0) { series.Points.Add(new SeriesPoint("Undefined", new double[] { 1 })); series.Label.PointOptions.PointView = PointView.SeriesName; } else { series.Label.PointOptions.PointView = PointView.ArgumentAndValues; for (int i = 0; i < _Data.Count; i++) { string argument = _Data[i].Key.Trim(); if (String.IsNullOrEmpty(argument)) { argument = "Undefined " + undefined; undefined++; } series.Points.Add(new SeriesPoint(argument, new double[] { _Data[i].Value })); } } chart.Legend.Visible = _ShowLegend; chart.BorderOptions.Visible = false; chart.Series.AddRange(new Series[] { series }); series = null; XYDiagram diagram = chart.Diagram as XYDiagram; if (diagram != null && diagram.AxisX != null) { diagram.AxisX.Label.ResolveOverlappingOptions.AllowStagger = true; chart.Series[0].Label.ResolveOverlappingMode = ResolveOverlappingMode.JustifyAllAroundPoint; chart.Series[0].Label.ResolveOverlappingMinIndent = 15; } chart.ExportToImage(stream, ImageFormat.Bmp); return(stream); } catch { if (series != null) { series.Dispose(); } throw; } } catch { if (stream != null) { stream.Dispose(); } throw; } } }
private void SaveChartImageToFile(ChartControl chart, ImageFormat format, String fileName) { // Create an image in the specified format from the chart // and save it to the specified path. chart.ExportToImage(fileName, format); }
public void LoadGraph() { if (_report.State != Report.StateEnum.Executed) { return; } bool rotateGraph = false; bool rotateAxes = ((_report.GraphOptions & OlapReport.GraphOptionsEnum.RotateAxes) > 0); int seriesPosCount = (rotateAxes ? _report.Cellset.Axis1PosCount: _report.Cellset.Axis0PosCount); int seriesMemCount = (rotateAxes ? _report.Cellset.Axis1TupleMemCount: _report.Cellset.Axis0TupleMemCount); int catPosCount = (rotateAxes ? _report.Cellset.Axis0PosCount: _report.Cellset.Axis1PosCount); int catMemCount = (rotateAxes ? _report.Cellset.Axis0TupleMemCount: _report.Cellset.Axis1TupleMemCount); if (seriesPosCount > 256) { seriesPosCount = 256; } if (catPosCount > 1024) { catPosCount = 1024; } bool showValues = (_report.GraphOptions & OlapReport.GraphOptionsEnum.ShowValues) > 0; bool showSeries = (_report.GraphOptions & OlapReport.GraphOptionsEnum.ShowSeries) > 0; bool showCats = (_report.GraphOptions & OlapReport.GraphOptionsEnum.ShowCategories) > 0; bool setScaling = (_report.GraphOptions & OlapReport.GraphOptionsEnum.SetScaling) > 0; // create series for (int i = 0; i < seriesPosCount; i++) { string name = ""; for (int j = 0; j < seriesMemCount; j++) { name += (j == 0 ? "" : " | ") + (rotateAxes ? _report.Cellset.GetCellsetMember(1, j, i).Name : _report.Cellset.GetCellsetMember(0, j, i).Name); } Series series = new Series(); series.Name = name; _chCtrl.Series.Add(series); // type if (_report.GraphType == OlapReport.GraphTypeEnum.Pie) { // limit number of series if (seriesPosCount > 6) { seriesPosCount = 6; } // disable scaling for pie setScaling = false; series.ChangeView(ViewType.Pie); PiePointOptions ppo = (PiePointOptions)series.PointOptions; PieSeriesView psw = (PieSeriesView)series.View; PieSeriesLabel psl = (PieSeriesLabel)series.Label; psl.Position = PieSeriesLabelPosition.TwoColumns; series.ShowInLegend = false; // cause it's shown in pie anyway showValues = true; showCats = true; this.chkCat.Checked = true; this.chkCat.Disabled = true; this.chkValues.Checked = true; this.chkValues.Disabled = true; } else { if (_report.GraphType == OlapReport.GraphTypeEnum.BarVertical) { series.ChangeView(ViewType.Bar); } else if (_report.GraphType == OlapReport.GraphTypeEnum.BarHorizontal) { series.ChangeView(ViewType.Bar); rotateGraph = true; } else if (_report.GraphType == OlapReport.GraphTypeEnum.StackedBarVertical) { series.ChangeView(ViewType.StackedBar); } else if (_report.GraphType == OlapReport.GraphTypeEnum.StackedBarHorizontal) { series.ChangeView(ViewType.StackedBar); rotateGraph = true; } else if (_report.GraphType == OlapReport.GraphTypeEnum.LineHorizontal) { series.ChangeView(ViewType.Line); } series.LegendText = name; series.ShowInLegend = true; series.ValueScaleType = ScaleType.Numerical; series.Visible = true; // labels orientation XYDiagram diag = (XYDiagram)_chCtrl.Diagram; diag.Rotated = rotateGraph; if (rotateGraph) { diag.AxisY.Label.Antialiasing = true; diag.AxisY.Label.Angle = 315; } else { diag.AxisX.Label.Antialiasing = true; diag.AxisX.Label.Angle = 315; } // if scaling if (setScaling) { diag.AxisY.Visible = false; } // if(setScaling) // { // // hide axis, cause it won't display real values // if(seriesPosCount<10) // diag.AxisY.Visible=false; // if(i<10) // { // SecondaryAxisY axisY=new SecondaryAxisY(name); // // axisY.Alignment=AxisAlignment.Near; // axisY.Title.Text = name; // axisY.Title.Visible = true; // axisY.Title.Font=new Font(axisY.Title.Font.Name, 10); // axisY.Label.Antialiasing=true; // axisY.Label.Angle=315; // // diag.SecondaryAxesY.Add(axisY); // ((XYDiagramSeriesViewBase)series.View).AxisY = axisY; // } // } } // prepare scaling ranges double scalingMin = double.MaxValue; double scalingMax = double.MinValue; if (setScaling) { for (int l = 0; l < catPosCount; l++) { string val = (rotateAxes ? _report.Cellset.GetCell(l, i).Value : _report.Cellset.GetCell(i, l).Value); double dVal = 0; double.TryParse(val, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out dVal); if (dVal < scalingMin) { scalingMin = dVal; } if (dVal > scalingMax) { scalingMax = dVal; } } } scalingMin = scalingMin - (scalingMax - scalingMin) * 0.1; // set data for (int l = 0; l < catPosCount; l++) { string argument = ""; for (int m = 0; m < catMemCount; m++) { argument += (m == 0 ? "" : " | ") + (rotateAxes ? _report.Cellset.GetCellsetMember(0, m, l).Name : _report.Cellset.GetCellsetMember(1, m, l).Name); } string val = (rotateAxes ? _report.Cellset.GetCell(l, i).Value : _report.Cellset.GetCell(i, l).Value); string fVal = (rotateAxes ? _report.Cellset.GetCell(l, i).FormattedValue : _report.Cellset.GetCell(i, l).FormattedValue); double dVal = 0; double.TryParse(val, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out dVal); if (setScaling) { dVal = (scalingMax - scalingMin == 0 ? 0 : (scalingMin + dVal) / (scalingMax - scalingMin)); } // custom point label string customLabel = string.Empty; if (!showValues && !showSeries && !showCats) { series.Label.Visible = false; } else { customLabel = (showSeries ? series.Name : string.Empty); customLabel += (showCats ? (customLabel != string.Empty ? " | " : string.Empty) + argument : string.Empty); customLabel += (showValues ? (customLabel != string.Empty ? ": " : string.Empty) + fVal : string.Empty); } CustomChartSeriesPoint sp = new CustomChartSeriesPoint(argument, dVal, customLabel); series.Points.Add(sp); } } ChartTitle title = new ChartTitle(); title.Alignment = StringAlignment.Center; title.Lines = new string[] { _report.Name, _report.Description }; _chCtrl.Titles.Add(title); if (_report.GraphTheme != null && _report.GraphTheme != "") { _chCtrl.AppearanceName = _report.GraphTheme; } _chCtrl.Width = AdjustGraphSize(_report.GraphWidth); _chCtrl.Height = AdjustGraphSize(_report.GraphHeight); string imgNamePrefix = _report.GetType().Name + _report.ID.ToString(); //delete older images of same report string[] filePaths = System.IO.Directory.GetFiles(FI.Common.AppConfig.TempDir, imgNamePrefix + "*.PNG"); if (filePaths != null && filePaths.Length > 0) { for (int j = 0; j < filePaths.Length; j++) { try { System.IO.File.Delete(filePaths[j]); } catch (Exception exc) { //do nothing exc = null; } } } //write to file and display, it will overwite itself if needed string imgName = imgNamePrefix + "." + DateTime.Now.ToString("yyyyMMddHHssfff") + ".PNG"; string imgVirtPath = Request.ApplicationPath + "/" + FI.Common.AppConfig.TempVirtualDir + "/" + imgName; string imgPhysPath = FI.Common.AppConfig.TempDir + @"\" + imgName; _chCtrl.ExportToImage(imgPhysPath, System.Drawing.Imaging.ImageFormat.Png); System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image(); img.ImageUrl = imgVirtPath; this.cellGraph.Controls.Add(img); }
private void CreateStatisticTheme(string LayerName) { //创建组 string GroupName = "统计专题_" + LayerName; int GroupID = Program.sgworld.ProjectTree.CreateGroup(GroupName); //根据获取的位置及表中的值建立 if (StaThemePos != null) { this.progressBarControl1.Properties.Minimum = 0; this.progressBarControl1.Properties.Maximum = StaThemePos.Count; this.progressBarControl1.Properties.Step = 1; this.progressBarControl1.Position = 0; for (int i = 0; i < StaThemePos.Count; i++) { //根据图表类型获取字段值根据设置生成图像 #region ChartControl Chart3D = new ChartControl(); ChartTitle chartTitle1 = new ChartTitle(); Chart3D.Titles.Add(chartTitle1); string AValue = ""; switch (this.comboBoxChartType.Text) { case "柱状图": //每个字段对应一个Series,字段名以及该要素该字段的值构成一个Point foreach (DataGridViewRow ARow in this.dataGridView3.Rows) { Series Aseries = new Series("Aseries", ViewType.Bar3D); AValue = this.dataGridView4.Rows[i].Cells[ARow.Cells[1].Value.ToString()].Value.ToString(); Aseries.Points.Add(new SeriesPoint(ARow.Cells[1].Value.ToString(), Convert.ToDouble(AValue))); Chart3D.Series.Add(Aseries); ((BarSeriesLabel)Aseries.Label).Visible = true; Font myFont = new Font(new FontFamily("宋体"),20); ((BarSeriesLabel)Aseries.Label).Font = myFont; ((BarSeriesLabel)Aseries.Label).BackColor = Color.FromArgb(0, 0, 0, 0); ((BarSeriesLabel)Aseries.Label).Border.Visible = false; ((BarSeriesLabel)Aseries.Label).TextColor = Color.Black; ((BarSeriesLabel)Aseries.Label).ResolveOverlappingMode = ResolveOverlappingMode.Default; Aseries.PointOptions.PointView = PointView.ArgumentAndValues; //是否勾选百分比 //if (this.checkPercent.Checked) // Aseries.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent; ((Bar3DSeriesView)Aseries.View).Model = Bar3DModel.Cylinder; //修改柱状体颜色 ((Bar3DSeriesView)Aseries.View).Color = ARow.Cells[0].Style.BackColor; ((XYDiagram3D)Chart3D.Diagram).AxisX.GridLines.Visible = false; ((XYDiagram3D)Chart3D.Diagram).AxisX.Label.Visible = false; ((XYDiagram3D)Chart3D.Diagram).AxisY.GridLines.Visible = false; ((XYDiagram3D)Chart3D.Diagram).AxisY.Label.Visible = false; ((XYDiagram3D)Chart3D.Diagram).AxisY.Interlaced = false; ((XYDiagram3D)Chart3D.Diagram).BackColor = Color.FromArgb(0, 0, 0, 0); } break; case "堆叠柱状图": //每个字段对应一个Series,每个Series一个Point,Argument值相同,Value值对应各字段值,起码2个Series才有堆叠效果 foreach (DataGridViewRow ARow in this.dataGridView3.Rows) { Series Aseries = new Series("Aseries", ViewType.StackedBar3D); AValue = this.dataGridView4.Rows[i].Cells[ARow.Cells[1].Value.ToString()].Value.ToString(); Aseries.Points.Add(new SeriesPoint(this.dataGridView4.Rows[i].Cells[0].Value.ToString(), Convert.ToDouble(AValue))); Chart3D.Series.Add(Aseries); ((BarSeriesLabel)Aseries.Label).Visible = true; Font myFont = new Font(new FontFamily("宋体"), 20); ((BarSeriesLabel)Aseries.Label).Font = myFont; ((BarSeriesLabel)Aseries.Label).BackColor = Color.FromArgb(0, 0, 0, 0); ((BarSeriesLabel)Aseries.Label).Border.Visible = false; ((BarSeriesLabel)Aseries.Label).TextColor = Color.Black; ((BarSeriesLabel)Aseries.Label).ResolveOverlappingMode = ResolveOverlappingMode.Default; Aseries.PointOptions.PointView = PointView.ArgumentAndValues; //是否勾选百分比 //if (this.checkPercent.Checked) // Aseries.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent; ((Bar3DSeriesView)Aseries.View).Model = Bar3DModel.Cylinder; //修改柱状体颜色 ((Bar3DSeriesView)Aseries.View).Color = ARow.Cells[0].Style.BackColor; ((XYDiagram3D)Chart3D.Diagram).AxisX.GridLines.Visible = false; ((XYDiagram3D)Chart3D.Diagram).AxisX.Label.Visible = false; ((XYDiagram3D)Chart3D.Diagram).AxisY.GridLines.Visible = false; ((XYDiagram3D)Chart3D.Diagram).AxisY.Label.Visible = false; ((XYDiagram3D)Chart3D.Diagram).AxisY.Interlaced = false; ((XYDiagram3D)Chart3D.Diagram).BackColor = Color.FromArgb(0, 0, 0, 0); } break; case "饼图": //每个要素仅含一个Series,每个字段对应一个Point,分别由字段名和字段值组成 Series Aseries1 = new Series("Aseries1", ViewType.Pie3D); Palette Colorlist = new Palette("Colorlist"); foreach (DataGridViewRow ARow in this.dataGridView3.Rows) { AValue = this.dataGridView4.Rows[i].Cells[ARow.Cells[1].Value.ToString()].Value.ToString(); Aseries1.Points.Add(new SeriesPoint(ARow.Cells[1].Value.ToString(), Convert.ToDouble(AValue))); //Aseries1.Points.Add(new SeriesPoint(ARow.Cells[1].Value.ToString(), 50)); Colorlist.Add(ARow.Cells[0].Style.BackColor); } Chart3D.Series.Add(Aseries1); //修改饼颜色 Chart3D.PaletteRepository.Add("Colorlist", Colorlist); Chart3D.PaletteName = "Colorlist"; Chart3D.PaletteBaseColorNumber = 0; ((Pie3DSeriesLabel)Aseries1.Label).Visible = true; Font myFont1 = new Font(new FontFamily("宋体"),10); ((Pie3DSeriesLabel)Aseries1.Label).Font = myFont1; ((Pie3DSeriesLabel)Aseries1.Label).BackColor = Color.FromArgb(0, 0, 0, 0); ((Pie3DSeriesLabel)Aseries1.Label).Border.Visible = false; ((Pie3DSeriesLabel)Aseries1.Label).TextColor = Color.Black; ((Pie3DSeriesLabel)Aseries1.Label).ResolveOverlappingMode = ResolveOverlappingMode.Default; Aseries1.PointOptions.PointView = PointView.ArgumentAndValues; //是否勾选百分比 if (this.checkPercent.Checked) { Aseries1.PointOptions.ValueNumericOptions.Format = DevExpress.XtraCharts.NumericFormat.Percent; Aseries1.PointOptions.ValueNumericOptions.Precision = 1; } break; default: break; } chartTitle1.Text = this.dataGridView4.Rows[i].Cells[0].Value.ToString(); chartTitle1.TextColor = Color.White; chartTitle1.WordWrap = true; Chart3D.BackColor = Color.FromArgb(0, 0, 0, 0); Chart3D.BorderOptions.Visible = false; Chart3D.Size =new Size(400,400); Chart3D.Legend.Visible = false; Chart3D.ExportToImage(Application.StartupPath + "temp_" + i + ".png", System.Drawing.Imaging.ImageFormat.Png); //使图片透明 Bitmap oldbmp = new Bitmap(Application.StartupPath + "temp_" + i + ".png"); Bitmap newbmp = new Bitmap(oldbmp.Width, oldbmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); newbmp.MakeTransparent(); for (int x = 0; x != oldbmp.Width; x++) { for (int y = 0; y != oldbmp.Height; y++) { Color AColor = oldbmp.GetPixel(x, y); if (!(AColor.A == 255 & AColor.R == 238 & AColor.G == 238 & AColor.B == 238)) { newbmp.SetPixel(x, y, Color.FromArgb(AColor.A, AColor.R, AColor.G, AColor.B)); } } } newbmp.Save(Application.StartupPath + "temp2_" + i + ".png", System.Drawing.Imaging.ImageFormat.Png); oldbmp.Dispose(); #endregion //创建Label,后删除图片 ILabelStyle61 cLabelStyle = null; ITerrainImageLabel61 cImageLabel = null; //根据设置创建标签风格 SGLabelStyle eLabelStyle = SGLabelStyle.LS_DEFAULT; cLabelStyle = Program.sgworld.Creator.CreateLabelStyle(eLabelStyle); //随图缩放 cLabelStyle.LimitScreenSize = true; //最大可视高度 cLabelStyle.MaxViewingHeight = 50000; //最小可视高度 //cLabelStyle.MinViewingHeight = 10; cLabelStyle.PivotAlignment = "Bottom,Left"; cImageLabel = Program.sgworld.Creator.CreateImageLabel(StaThemePos[i], Application.StartupPath + "temp2_" + i + ".png", cLabelStyle, GroupID, this.dataGridView4.Rows[i].Cells[0].Value.ToString()); File.Delete(Application.StartupPath + "temp_" + i + ".png"); File.Delete(Application.StartupPath + "temp2_" + i + ".png"); System.Windows.Forms.Application.DoEvents(); this.progressBarControl1.PerformStep(); } } }
private void btnExport_Click(object sender, EventArgs e) { try { DataTable dt = this.gridControl1.DataSource as DataTable; if (dt == null || dt.Rows.Count == 0) { MessageDxUtil.ShowTips("没有数据需要导出!"); return; } string saveDocFile = FileDialogHelper.SaveExcel(string.Format("{0}.xls", ReportTitle), "C:\\"); if (!string.IsNullOrEmpty(saveDocFile)) { Workbook workbook = new Workbook(); Worksheet worksheet = workbook.Worksheets[0]; worksheet.PageSetup.Orientation = PageOrientationType.Landscape; //横向打印 worksheet.PageSetup.Zoom = 100; //以100%的缩放模式打开 worksheet.PageSetup.PaperSize = PaperSizeType.PaperA4; #region 表头及说明信息 Range range; Cell cell; string content; int colSpan = 3; range = worksheet.Cells.CreateRange(0, 0, 1, colSpan); range.Merge(); range.RowHeight = 20; range.SetStyle(CreateTitleStyle(workbook)); cell = range[0, 0]; cell.PutValue(ReportTitle); range = worksheet.Cells.CreateRange(1, 0, 1, colSpan); range.Merge(); range.RowHeight = 15; cell = range[0, 0]; content = string.Format("统计报表详细列表如下:"); cell.PutValue(content); #endregion #region 生成报表头部表格 Style headStyle = CreateStyle(workbook, true); Style normalStyle = CreateStyle(workbook, false); int startRow = 2; int startCol = 0; int index = 0; foreach (DataColumn col in dt.Columns) { range = worksheet.Cells.CreateRange(startRow, index, 2, 1); range.Merge(); range.SetStyle(headStyle); cell = range[0, 0]; cell.PutValue(col.ColumnName); cell.SetStyle(headStyle); index++; } #endregion //写入数据到Excel startRow = startRow + 2; for (int i = 0; i < dt.Rows.Count; i++) { startCol = 0; for (int j = 0; j < dt.Columns.Count; j++) { DataRow dr = dt.Rows[i]; cell = worksheet.Cells[startRow, startCol]; cell.PutValue(dr[j]); cell.SetStyle(normalStyle); startCol++; } startRow++; } //写入图注 startRow += 1;//跳过1行 range = worksheet.Cells.CreateRange(startRow++, 0, 1, colSpan); range.Merge(); range.RowHeight = 15; cell = range[0, 0]; cell.PutValue("以曲线图展示如下:"); //插入图片到Excel里面 using (MemoryStream stream = new MemoryStream()) { stream.Position = 0; ChartControl chart = (ChartControl)chartControl1.Clone(); chart.Size = new Size(800, 400); chart.ExportToImage(stream, ImageFormat.Jpeg); worksheet.Pictures.Add(startRow, 0, stream); } workbook.Save(saveDocFile); if (MessageDxUtil.ShowYesNoAndTips("保存成功,是否打开文件?") == System.Windows.Forms.DialogResult.Yes) { System.Diagnostics.Process.Start(saveDocFile); } } } catch (Exception ex) { LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmLineHistoryReport)); MessageDxUtil.ShowError(ex.Message); return; } }
/// <summary> /// 导出图片 /// </summary> /// <param name="filename"></param> /// <param name="ext"></param> private void ExportToCore(ChartControl chart, string filename, string ext) { try { if (chart != null) { var currentCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; if (ext == "rtf") { chart.ExportToRtf(filename); } else if (ext == "pdf") { chart.ExportToPdf(filename); } else if (ext == "mht") { chart.ExportToMht(filename); } else if (ext == "html") { chart.ExportToHtml(filename); } else if (ext == "xls") { chart.ExportToXls(filename); } else if (ext == "xlsx") { chart.ExportToXlsx(filename); } else { ImageFormat currentImageFormat = null; if (ext.ToLower().Contains("bmp")) { currentImageFormat = ImageFormat.Bmp; } else if (ext.ToLower().Contains("jpg")) { currentImageFormat = ImageFormat.Jpeg; } else if (ext.ToLower().Contains("png")) { currentImageFormat = ImageFormat.Png; } else if (ext.ToLower().Contains("gif")) { currentImageFormat = ImageFormat.Gif; } chart.ExportToImage(filename, currentImageFormat); } Cursor.Current = currentCursor; } } catch (Exception ex) { LogHelper.Error("Kgl_StateChg_ExportToCore" + ex.Message + ex.StackTrace); } }
public Stream CreateChart() { using (ChartControl chart = new ChartControl()) { if (_Width.HasValue) { chart.Width = _Width.Value; } if (_Height.HasValue) { chart.Height = _Height.Value; } int undefined = 1; MemoryStream stream = new MemoryStream(); try { Series series = new Series("Chart", _ViewType); try { if (series.Label is DevExpress.XtraCharts.PieSeriesLabel) { ((DevExpress.XtraCharts.PieSeriesLabel)series.Label).Position = PieSeriesLabelPosition.Inside; } if (_ViewType == ViewType.Pie) { series.Label.TextPattern = "{A}: {VP:P0}"; } if (_Data == null || _Data.Count == 0) { series.Points.Add(new SeriesPoint("Undefined", new double[] { 1 })); series.Label.TextPattern = "{S}"; } else { series.Label.TextPattern = "{A}: {V:F1}"; for (int i = 0; i < _Data.Count; i++) { string argument = _Data[i].Key.Trim(); if (String.IsNullOrEmpty(argument)) { argument = "Undefined " + undefined; undefined++; } series.Points.Add(new SeriesPoint(argument, new double[] { _Data[i].Value })); } } chart.Legend.Visibility = _ShowLegend; chart.BorderOptions.Visibility = DevExpress.Utils.DefaultBoolean.False; chart.Series.AddRange(new Series[] { series }); series = null; XYDiagram diagram = chart.Diagram as XYDiagram; if (diagram != null && diagram.AxisX != null) { diagram.AxisX.Label.ResolveOverlappingOptions.AllowStagger = true; } ; chart.ExportToImage(stream, ImageFormat.Png); stream.Position = 0; return(stream); } catch { if (series != null) { series.Dispose(); } throw; } } catch { if (stream != null) { stream.Dispose(); } throw; } } }