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

后端 未结 7 1406
礼貌的吻别
礼貌的吻别 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:22

    Interop has the fastest method called CopyFromRecordset but ADODB library has to be used

    Definitely the fastest way/method and I have tried a few. Perhaps, not easy to use but the speed is astonishing:

    https://docs.microsoft.com/en-us/office/vba/api/excel.range.copyfromrecordset

    a short sample:

    using ADODB;
    using Microsoft.Office.Interop;
    
    //--- datatable --- already exists
    DataTable dt_data = new DataTable();
    //--- or your dt code is here ..........
    
    
    //--- mine has 3 columns ------
    
    //--- code to populate ADO rs with DataTable data --- nothing special
    //--- create empty rs .....
    ADODB.Recordset rs = new ADODB.Recordset();
    rs.CursorType = CursorTypeEnum.adOpenKeyset;
    rs.CursorLocation = CursorLocationEnum.adUseClient;
    rs.LockType = LockTypeEnum.adLockOptimistic;
    rs.Fields.Append("employee_id",DataTypeEnum.adBSTR,255,FieldAttributeEnum.adFldIsNullable);
    rs.Fields.Append("full_name", DataTypeEnum.adBSTR, 255, FieldAttributeEnum.adFldIsNullable);
    rs.Fields.Append("start_date", DataTypeEnum.adBSTR, 10, FieldAttributeEnum.adFldIsNullable);
    rs.Open();
    
    //--- populate ADO rs with DataTable data ----    
    for (int i = 0; i < dt_data.Rows.Count; i++)
    {
        rs.AddNew();
        rs.Fields["employee_id"].Value = dt_data.Rows[i]["employee_id"].ToString();
        rs.Fields["full_name"].Value = dt_data.Rows[i]["full_name"].ToString();
        //--- if date is empty......
        if (dt_data.Rows[i]["start_date"].ToString().Length > 0)
        {
            rs.Fields["start_date"].Value = dt_data.Rows[i]["start_date"].ToString();
        }
        rs.Update();
    }
    
    Microsoft.Office.Interop.Excel.Application xlexcel;
    Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
    Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
    object misValue = System.Reflection.Missing.Value;
    xlexcel = new Microsoft.Office.Interop.Excel.Application();
    xlexcel.Visible = true;
    
    
    xlWorkBook = xlexcel.Workbooks.Add(misValue);
    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    
    //--- populate columns from rs --
    for (int i = 0; i < rs.Fields.Count; i++)
    {
        xlWorkSheet.Cells[1, i + 1] = rs.Fields[i].Name.ToString();
    };
    
    //----- .CopyFromRecordset method -- (rs object, MaxRows, MaxColumns) --- in this case 3 columns but it can 1,2,3 etc ------
    xlWorkSheet.Cells[2, 1].CopyFromRecordset(CloneFilteredRecordset(rs), rs.RecordCount, 3);
    
    0 讨论(0)
提交回复
热议问题