How to speed up dumping a DataTable into an Excel worksheet?

后端 未结 7 1421
礼貌的吻别
礼貌的吻别 2020-12-15 07:37

I have the following routine that dumps a DataTable into an Excel worksheet.

    private void RenderDataTableOnXlSheet(DataTable dt, Excel.Worksheet xlWk,          


        
7条回答
  •  长情又很酷
    2020-12-15 08:06

    I agree with Charles. Interop is really slow. But try this:

    private void RenderDataTableOnXlSheet(DataTable dt, Excel.Worksheet xlWk, 
                                        string [] columnNames, string [] fieldNames)
    {
        // render the column names (e.g. headers)
        int columnLength = columnNames.Length;
        for (int i = 0; i < columnLength; i++)
            xlWk.Cells[1, i + 1] = columnNames[i];
    
        // render the data 
            int fieldLength = fieldNames.Length;
            int rowCount = dt.Rows.Count;
            for (int j = 0; j < rowCount; j++)
            { 
                for (int i = 0; i < fieldLength; i++)
                {
                    xlWk.Cells[j + 2, i + 1] = dt.Rows[j][fieldNames[i]].ToString();
                }
            }
    }
    

    HTH

提交回复
热议问题