将图表导出到Excel文件

时间:2018-12-15 11:09:05

标签: c# excel winforms charts export

我是C# Programming的新朋友。我正在创建使用winform application的{​​{1}}。此System.Windows.Forms.DataVisualization Chart包含多个系列。我想将该图表数据导出到Excel文件。

要将数据添加到我正在使用的图表中

chart

dt是 chart.Series[mSeries].Points.AddXY(dt, avgData); current DateTime

所以我的Excel文件看起来像

第一列为data,第二列为Series Name,第三列包含DateTime

所以,任何人都可以告诉我我该怎么做。

预先感谢

1 个答案:

答案 0 :(得分:1)

您可以参考以下solution。首先,您需要添加对COM的Microsoft Excel对象库的引用。有关如何add的信息,请参见此链接。然后下一步非常简单。您将需要从上面的链接中添加代码,并用自定义数据替换在Excel中输入的数据。

这是链接中显示的代码。

 private void button1_Click(object sender, EventArgs e)
 {
     Excel.Application xlApp;
     Excel.Workbook xlWorkBook;
     Excel.Worksheet xlWorkSheet;
     object misValue = System.Reflection.Missing.Value;

     xlApp = new Excel.Application();
     xlWorkBook = xlApp.Workbooks.Add(misValue);
     xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

     for (int i = 0; i < chart1.Series.Count; i++)
     {
      xlWorkSheet.Cells[1, 1] = "";
      xlWorkSheet.Cells[1, 2] = "DateTime";//put your column heading here
      xlWorkSheet.Cells[1, 3] = "Data";// put your column heading here

      for (int j = 0; j < chart1.Series[i].Points.Count; j++)
      {
       xlWorkSheet.Cells[j + 2 , 2] = chart1.Series[i].Points[j].XValue;
       xlWorkSheet.Cells[j + 2 , 3] = chart1.Series[i].Points[j].YValues[0];
      }
     }

     Excel.Range chartRange;

     Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
     Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
     Excel.Chart chartPage = myChart.Chart;

     chartRange = xlWorkSheet.get_Range("B2", "c5");//update the range here
     chartPage.SetSourceData(chartRange, misValue);
     chartPage.ChartType = Excel.XlChartType.xlColumnClustered;

     xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
     xlWorkBook.Close(true, misValue, misValue);
     xlApp.Quit();

     releaseObject(xlWorkSheet);
     releaseObject(xlWorkBook);
     releaseObject(xlApp);

     MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
 }

 private void releaseObject(object obj)
 {
  try
  {
   System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
   obj = null;
  }
  catch (Exception ex)
  {
   obj = null;
   MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
   }
   finally
   {
    GC.Collect();
   }
 }

当您单击导出按钮时,只需用自定义数据和中提琴替换代码中的单元格和数据,它将为您导出。