如何快速将数据从DataTable复制到Excel?

时间:2014-11-04 02:11:49

标签: c# excel datatable

我从谷歌获得以下代码,将数据表快速复制到excel。逐个细胞技术非常慢。

代码: -

Excel.Application excelApp = new Excel.Application();
excelApp.DisplayAlerts = false;

Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
xlWorkBook = excelApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;


xlWorkSheet.Cells[1, 1] = "Name";
xlWorkSheet.Cells[1, 2] = "Index";
xlWorkSheet.Cells[1, 3] = "Cat";
xlWorkSheet.Cells[1, 4] = "CatNumber";
xlWorkSheet.Cells[1, 5] = "ID";
xlWorkSheet.Cells[1, 6] = "Type";
xlWorkSheet.Cells[1, 7] = "Description";
xlWorkSheet.Cells[1, 8] = "Sou";
xlWorkSheet.Cells[1, 9] = "IID";
xlWorkSheet.Cells[1, 10] = "Time";
xlWorkSheet.Cells[1, 11] = "TimeW";
xlWorkSheet.Cells[1, 12] = "User";


if (dt1.TableName == Convert.ToString(objType1.Name))
{
    object[,] arr = new object[dt1.Rows.Count, dt1.Columns.Count];

    for (int r = 0; r < dt1.Rows.Count; r++)
    {
        DataRow dr = dt1.Rows[r];
        for (int c = 0; c < dt1.Columns.Count; c++)
        {
            arr[r, c] = dr[c];
        }
    }

    //Set Excel Range to Paste the Data
    Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[2, 1];
    Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1 + dt1.Rows.Count, dt1.Columns.Count];
    Microsoft.Office.Interop.Excel.Range range = xlWorkSheet.get_Range(c1, c2);

    //Fill Array in Excel
    range.Value2 = arr;

注意:dt1是我拥有的具有多个不同数据类型列的数据表。 我将文件保存到扩展名abc.xls。

现在,我认为我面临的问题是,每当描述很大时,它会在将特定描述复制到range.value2时抛出异常HRESULT OX800A03EC。我现在陷入了困境。

请帮助解决方案。 谢谢!

0 个答案:

没有答案