///
/// Excel one-time write large amounts of data quickly
///
/// workbook path
/// to write the name of the worksheet
Private void WriteExcel (path String, String sheetName)
{
Microsoft.Office.Interop.Excel.Application new new Microsoft.Office.Interop.Excel.Application App = () ;
app.Visible = false; // do not show EXCEL
app.DisplayAlerts = false; // no message
app.ScreenUpdating = false; // stop updating the screen, speed up
workbooks wbs = app.Workbooks; // get the workbook
_Workbook wb = wbs.Open (path); // open file
Sheets shs = wb.Worksheets; Sheets // file
System.Data.DataTable table = getDataTable (); // call getDataTable () method to get the memory table DataTable
CopyDataToSheet ( table, shs [sheetName]); // call the method, the data is written into DataTable in the Sheet
wb.Save(); //保存
wb.Close(); //关闭工作薄
app.Quit(); //关闭EXCEL
MessageBox.Show("OK");
}
//快速写入(先写入数组,然后一次性将数组写入到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);
}