1. 程式人生 > >C#:Excel一次性大量資料快速寫入

C#:Excel一次性大量資料快速寫入

//呼叫的方法
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();

string filename = StartupFilePath + "\\a.xlsx" + ;
app.Visible = false; //不顯示EXCEL
app.DisplayAlerts = false; //不提示資訊
app.ScreenUpdating = false; //停止更新螢幕,加快速度
Workbooks wbs = app.Workbooks; //獲取工作薄
_Workbook wb = wbs.Open(filename); //開啟檔案
Sheets shs = wb.Worksheets; //檔案中的Sheets

System.Data.DataTable table = dbh.getDataSet(DealFun(sql)).Tables[0];
CopyDataToSheet(table, shs[1]); //呼叫方法,將DataTable裡的資料寫入到第2個Sheet中

wb.Save(); //儲存
wb.Close(); //關閉工作薄
app.Quit(); //關閉EXCEL
//快速寫入(先寫入陣列,然後一次性將陣列寫入到EXCEL中)
private void CopyDataToSheet(System.Data.DataTable Table, _Worksheet Sheet)
        {
            int colCount, rowCount;
            colCount = Table.Columns.Count;
            rowCount = Table.Rows.Count;
            Range range;
            
            //寫入標題行
            range = Sheet.get_Range("A1", Missing.Value);
            range = range.get_Resize(1, colCount);
            object[,] headerData = new object[1, colCount];
            for (int iCol = 0; iCol < colCount; iCol++)
            {
                headerData[0, iCol] = Table.Columns[iCol].ColumnName;
            }
            range.set_Value(Missing.Value, headerData);

            //寫入資料行
            range = Sheet.get_Range("A2", Missing.Value);
            range = range.get_Resize(rowCount, colCount);
            object[,] cellData = new object[rowCount, colCount];
            for (int iRow = 0; iRow < rowCount; iRow++)
            {
                for (int iCol = 0; iCol < colCount; iCol++)
                {
                    cellData[iRow, iCol] = Table.Rows[iRow][iCol].ToString();
                }
            }
            range.set_Value(Missing.Value, cellData);
        }
//龜速寫入,一個單元格一個的寫入,不建議使用。
private void CopyDataToSheet2(System.Data.DataTable Table, _Worksheet Sheet)
        {
            int i_col, i_row;
            i_col=1;
            i_row=1;
            foreach (DataColumn column in Table.Columns) //寫標題
            {
                Sheet.Cells[i_row, i_col] = column.ColumnName;
                i_col++;
            }

            i_row=2;
            foreach (DataRow dr in Table.Rows) //寫資料
            {
                i_col = 1;
                foreach (object obj in dr.ItemArray)
                {
                    Sheet.Cells[i_row, i_col] = dr[i_col - 1].ToString();
                    i_col++;
                }
                i_row++;
            }
        }