0

我正在尝试从中导出数据Datatable to Excel。数据表有8540 rows31 columns

下面的循环在 3500 条记录后某处中断:

for (int i = 0; i < Tbl.Rows.Count; i++)
{
    for (int j = 0; j < Tbl.Columns.Count; j++)
    {
         workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
    }
}

导出时是否有行数限制?还是我做错了什么?请帮忙!

我用于导出的代码是:

public static void ExportExcel(this DataTable Tbl, string ExcelFilePath = null)
{
    try
    {
        if (Tbl == null || Tbl.Columns.Count == 0)
            //throw new Exception("ExportToExcel: Null or empty input table!\n");
            Console.WriteLine("ExportToExcel: Null or empty input table!\n");

        // load excel, and create a new workbook
        Excel.Application excelApp = new Excel.Application();
        excelApp.Workbooks.Add();

        // single worksheet
        Excel._Worksheet workSheet = excelApp.ActiveSheet;

        // column headings
        for (int i = 0; i < Tbl.Columns.Count; i++)
        {
            workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName;
            workSheet.Cells[1, (i + 1)].Font.Bold = true;
            workSheet.Cells[1, (i + 1)].Font.Size = 12;
        }

        // rows
        for (int i = 0; i < Tbl.Rows.Count; i++)
        {
            // to do: format datetime values before printing
            for (int j = 0; j < Tbl.Columns.Count; j++)
            {
                workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
            }
        }

        // check fielpath
        if (ExcelFilePath != null && ExcelFilePath != "")
        {
            try
            {
                workSheet.SaveAs(ExcelFilePath);
                excelApp.Quit();
                //MessageBox.Show("Excel file saved!");
            }
            catch (Exception ex)
            {
                //throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"+ ex.Message);
                Console.WriteLine("ExportToExcel: Excel file could not be saved! Check filepath.\n"+ ex.Message);
            }
        }
        else    // no filepath is given
        {
            excelApp.Visible = true;
        }
    }
    catch (Exception ex)
    {
        //throw new Exception("ExportToExcel: \n" + ex.Message);
        Console.WriteLine("ExportToExcel: \n" + ex.Message); 
    }
}
4

1 回答 1

0

If I might offer an alternative: Use EPPLUS and its great LoadFromDataTable* Function - this would reduce your code to one line, it is magnitudes faster and it does not rely on Excel directly. Also: the library is free and can be included without licensing problems.

于 2013-07-05T11:45:50.700 回答