我有一个excel文件,里面有一个图表。如何将此图表导入Windows窗体应用程序?

时间:2017-07-12 15:04:55

标签: c# excel winforms

目前我的图表代码如下所示:

 private void chart1_Click(object sender, EventArgs e)
        {
            //create the Application object we can use in the member functions.
            Microsoft.Office.Interop.Excel.Application _excelApp = new Microsoft.Office.Interop.Excel.Application();
            _excelApp.Visible = true;

        string fileName = "C:/Users/Desktop/UP and DOWN data.xlsx"; 


        //open the workbook
        Workbook workbook = _excelApp.Workbooks.Open(fileName,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing);

        //select the first sheet        
        Worksheet worksheet = (Worksheet)workbook.Worksheets[1];

        //find the used range in worksheet
        Range excelRange = worksheet.UsedRange;

        //get an object array of all of the cells in the worksheet (their values)
        object[,] valueArray = (object[,])excelRange.get_Value(
                    XlRangeValueDataType.xlRangeValueDefault);
        System.Windows.Forms.DataVisualization.Charting.Series seriesUP = this.chart1.Series.Add("UP");
        System.Windows.Forms.DataVisualization.Charting.Series seriesDOWN = this.chart1.Series.Add("DOWN");
        seriesUP.ChartType = SeriesChartType.Spline;
        seriesDOWN.ChartType = SeriesChartType.Spline;
        //access the cells
        for (int row = 1; row <= worksheet.UsedRange.Rows.Count; ++row)
        {
            for (int col = 1; col <= worksheet.UsedRange.Columns.Count; ++col)
            {
                //access each cell
                if (row != 1)
                {

                    if (col == 1)//get UP data only
                        seriesUP.Points.AddXY(Convert.ToDouble(valueArray[row, col]), Convert.ToDouble(valueArray[row, col + 1]));
                    // Debug.Print(valueArray[row, col].ToString());
                    if (col == 3)//get DOWN data only

                        seriesDOWN.Points.AddXY(Convert.ToDouble(valueArray[row, col]), Convert.ToDouble(valueArray[row, col + 1]));
                }
            }
        }

        //clean up stuffs
        workbook.Close(false, Type.Missing, Type.Missing);
        Marshal.ReleaseComObject(workbook);

        _excelApp.Quit();
        Marshal.FinalReleaseComObject(_excelApp);
}

上面的内容试图绘制一个图表,这个图表对于大型数据集来说需要太长时间。如何访问同一工作簿并提取已在其上绘制的图表并在winform上显示该图表?

0 个答案:

没有答案