【问题标题】:Improving the Speed on Exporting Datagridview to Excel with Interop Excel使用 Interop Excel 提高将 Datagridview 导出到 Excel 的速度
【发布时间】:2017-01-18 16:02:33
【问题描述】:

我确实有一个按钮单击事件上的 c# 窗口应用程序,它使用 Microsoft Office 互操作 Excel 模块将 datagridview 导出到 Excel。

但我发现用于导出数据的时间很慢,我发现其他人正在使用 2D Array 方法来加快它。我确实尝试过,但我无法正确过滤掉它。

我之前确实尝试过手动关闭 Excel 计算,但它仍然没有帮助。对此有何建议?

这是我的代码:

//Create Excel Object.
            Microsoft.Office.Interop.Excel.Application objexcelapp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel._Workbook workbook = objexcelapp.Application.Workbooks.Add(Type.Missing);
            //objexcelapp.Columns.ColumnWidth = 30;
            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
            try
            {
                worksheet = workbook.ActiveSheet;
                worksheet.Name = "Daily Report";
                worksheet.Range["A1", "S1"].Interior.Color = Excel.XlRgbColor.rgbBurlyWood;

                for (int i = 1; i < dailyReportGridView.Columns.Count + 1; i++)
                {
                    if (i != 20 && i != 21 && i != 22)
                    {
                        objexcelapp.Cells[1, i] = dailyReportGridView.Columns[i - 1].HeaderText;
                    }
                }
                /*For storing Each row and column value to excel sheet*/
                for (int i = 0; i < dailyReportGridView.Rows.Count; i++)
                {
                    for (int j = 0; j < dailyReportGridView.Columns.Count; j++)
                    {
                        if (dailyReportGridView.Rows[i].Cells[j].Value != null && j != 19 && j != 20 && j != 21 && j != 22)
                        {
                            objexcelapp.Cells[i + 2, j + 1] = dailyReportGridView.Rows[i].Cells[j].Value.ToString();
                            AllBorders(objexcelapp.Cells[i + 2, j + 1].Borders);
                        }
                    }
                }
                objexcelapp.Columns.AutoFit();  //Auto fit all the data length to the column by Marcus 10-09-2016
                //Getting the location and file name of the excel to save from user.
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
                saveDialog.FilterIndex = 2;
                if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && dailyReportGridView.RowCount > 1)
                {
                    workbook.SaveAs(saveDialog.FileName);
                    MessageBox.Show("Excel File Had Been Saved!", "Success");
                }
                else
                {
                    MessageBox.Show("Operation Canceled.", "Failed To Save");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Export Excel Error" + ex.Message);
            }
            finally
            {
                objexcelapp.Quit();
                workbook = null;
                objexcelapp = null;
            }

【问题讨论】:

    标签: c# excel


    【解决方案1】:

    您要做的是避免设置单个单元格,因为每次更新都会触发整个 excel 文档(不仅是工作表)的刷新。我认为您可以关闭刷新(即重新计算单元格),但我不记得确切的方法名称,而且 MSDN 现在似乎有问题。您还想尝试设置整个范围而不是单个单元格,因为设置单元格比范围花费更多时间。

    如果您在其中任何一个方面需要具体帮助,我建议您针对这些问题提出新问题。

    这个问题的范围很广,但是是的,在性能方面使用 excel interop 很糟糕,如果用谷歌搜索,你可以找到帮助。

    【讨论】:

    • 嗨,是的,我用谷歌搜索了很多,我发现他们中的大多数都在使用范围方法。无论如何,你的意思是我关闭刷新会有帮助吗?
    • 是的,每个“集合”的很大一部分时间是重新计算整个工作簿的重新验证。
    • 我确实尝试将其关闭,但在导出时仍然很慢:(
    【解决方案2】:

    加快互操作的关键之一是一次设置整个范围值、边框、颜色等,而不是逐个单元格地设置。您已经在为内部颜色执行此操作。

    这里是一次设置值范围的示例
    How to optimize exporting data to excel in Excel Interop?

    另一种方法是将值和格式复制为 html 并将其粘贴到 Excel 中:

    Clipboard.SetText("<table><tr><td>a<td>b"); // most closing tags are optional
    worksheet.Paste();
    

    【讨论】:

    • 复制值和格式为html是什么意思?
    • @MarcusTan 我无法测试它,但是例如,如果您复制此文本 &lt;table style="border:1px solid red"&gt;&lt;tr&gt;&lt;td&gt;a&lt;td&gt;&lt;b&gt;b 并将其粘贴到 Excel 中,它应该在表格周围显示一个边框和一个粗体 b。或者您可以尝试在此处复制一些示例quackit.com/html/codes/tables/html_table_border.cfm
    • 我尝试使用工作表范围,但似乎不起作用
    【解决方案3】:

    DataTable dt = new DataTable();

            //Adding the Columns.
            foreach (DataGridViewColumn column in dgv1.Columns)
            {
                dt.Columns.Add(column.HeaderText, column.ValueType);
            }
    
            //Adding the Rows.
            foreach (DataGridViewRow row in dgv1.Rows)
            {
                dt.Rows.Add();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
                }
            }
    
    
    
            //Exporting to Excel.
            string folderPath = "C:\\Excel\\";
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt, "AssetMaster");
    
                //Set the color of Header Row.
                //A resembles First Column while C resembles Third column.
                wb.Worksheet(1).Cells("A1:C1").Style.Fill.BackgroundColor = XLColor.DarkGreen;
                for (int i = 1; i <= dt.Rows.Count; i++)
                {
                    //A resembles First Column while C resembles Third column.
                    //Header row is at Position 1 and hence First row starts from Index 2.
                    string cellRange = string.Format("A{0}:C{0}", i + 1);
                    if (i % 2 != 0)
                    {
                        //wb.Worksheet(1).Cells(cellRange).Style.Fill.BackgroundColor = XLColor.GreenYellow;
                    }
                    else
                    {
                        ////wb.Worksheet(1).Cells(cellRange).Style.Fill.BackgroundColor = XLColor.Yellow;
                    }
    
                }
                //Adjust widths of Columns.
                wb.Worksheet(1).Columns().AdjustToContents();
    
                //Save the Excel file.
                wb.SaveAs(folderPath + "DataGridViewExport.xlsx");
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2019-03-20
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 2013-09-11
      • 2011-08-07
      相关资源
      最近更新 更多