Fastest way to drop a DataSet into a worksheet

两盒软妹~` 提交于 2019-12-08 08:56:48

问题


A rather higeisch dataset with 16000 x 12 entries needs to be dumped into a worksheet.

I use the following function now:

        for (int r = 0; r < dt.Rows.Count; ++r)
        {
            for (int c = 0; c < dt.Columns.Count; ++c)
            {
                worksheet.Cells[c + 1][r + 1] = dt.Rows[r][c].ToString();
            }
        }

I rediced the example to the center piece


Here is what i implemented after reading the suggestion from Dave Zych. This works great.

    private static void AppendWorkSheet(Excel.Workbook workbook, DataSet data, String tableName)
    {
        Excel.Worksheet worksheet;
        if (UsedSheets == 0) worksheet = workbook.Worksheets[1];
        else worksheet = workbook.Worksheets.Add();
        UsedSheets++;
        DataTable dt = data.Tables[0];
        var valuesArray = new object[dt.Rows.Count, dt.Columns.Count];

        for (int r = 0; r < dt.Rows.Count; ++r)
        {
            for (int c = 0; c < dt.Columns.Count; ++c)
            {
                valuesArray[r, c] = dt.Rows[r][c].ToString();
            }
        }
        Excel.Range c1 = (Excel.Range)worksheet.Cells[1, 1];
        Excel.Range c2 = (Excel.Range)worksheet.Cells[dt.Rows.Count, dt.Columns.Count];
        Excel.Range range = worksheet.get_Range(c1, c2);
        range.Cells.Value2 = valuesArray;
        worksheet.Name = tableName;
    }

回答1:


Build a 2D array of your values from your DataSet, and then you can set a range of values in Excel to the values of the array.

object valuesArray = new object[dataTable.Rows.Count, dataTable.Columns.Count];
for(int i = 0; i < dt.Rows.Count; i++)
{
    //If you know the number of columns you have, you can specify them this way
    //Otherwise use an inner for loop on columns
    valuesArray[i, 0] = dt.Rows[i]["ColumnName"].ToString();
    valuesArray[i, 1] = dt.Rows[i]["ColumnName2"].ToString();
    ...
}

//Calculate the second column value by the number of columns in your dataset
//"O" is just an example in this case
//Also note: Excel is 1 based index
var sheetRange = worksheet.get_Range("A2:O2", 
    string.Format("A{0}:O{0}", dt.Rows.Count + 1));

sheetRange.Cells.Value2 = valuesArray;

This is much, much faster than looping and setting each cell individually. If you're setting each cell individually, you have to talk to Excel through COM (for lack of a better phrase) for each cell (which in your case is ~192,000 times), which is incredibly slow. Looping, building your array and only talking to Excel once removes much of that overhead.



来源:https://stackoverflow.com/questions/13184191/fastest-way-to-drop-a-dataset-into-a-worksheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!