导出到Excel花费太多时间在C#中导出数据

时间:2018-02-21 09:33:55

标签: c# sql asp.net

protected void btn_export_Click(object sender, EventArgs e)
{
    DataTable dtdata = new DataTable();
    dtdata = clsDataAccess.ExecuteDataTable("select * from Mst_Record");
    string data = null;
    int i = 0;
    int j = 0;

    Excel1.Application xlApp;
    Excel1.Workbook xlWorkBook;
    Excel1.Worksheet xlWorkSheet;
    object misValue = System.Reflection.Missing.Value;

    xlApp = new Excel1.Application();
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Excel1.Worksheet)xlWorkBook.Worksheets.get_Item(1);




    for (i = 0; i <= dtdata.Rows.Count - 1; i++)
    {
        for (j = 0; j <= dtdata.Columns.Count - 1; j++)
        {
            data = dtdata.Rows[i].ItemArray[j].ToString();
            xlWorkSheet.Cells[i + 1, j + 1] = data;
        }
    }
    string strfilename = "csharp.net-informations" + DateTime.Now.ToString("dd-MMM-yyyy") + ".xls";
    xlWorkBook.SaveAs(strfilename, Excel1.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel1.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();

    releaseObject(xlWorkSheet);
    releaseObject(xlWorkBook);
    releaseObject(xlApp);
    System.Windows.Forms.MessageBox.Show("Excel file created and saved in C Drive");


}

**以上SQL查询返回45000行并将此数据导出到Excel中。 它继续处理半小时,然后也没有打开excel。 还有其他更好的办法吗?****

1 个答案:

答案 0 :(得分:0)

您可以使用OLEDB将数据写入Excel。请参阅此SO线程Write Data to Excel using Oledb

这很快,不需要Excel对象