.NET開發人員首選的方法,通過COM組件調用Office軟件本身來實現文件的創建和讀寫,但是數據量較大的時候異常緩慢;如下代碼所示已經做了優化,將一個二維對象數組賦值到一個單元格區域中(下面的代碼中只能用于導出列數不多于26列的數據導出):
Office PIA
string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int colCharsetLen = colCharset.Length;
if (dt.Columns.Count > colCharsetLen)
{
finalColLetter = colCharset.Substring(
(dt.Columns.Count - 1) / colCharsetLen - 1, 1);
}
finalColLetter += colCharset.Substring(
(dt.Columns.Count - 1) % colCharsetLen, 1);
Excel.Worksheet sheet = (Excel.Worksheet)workbook.Sheets.Add(
workbook.Sheets.get_Item(++sheetIndex),
Type.Missing, 1, Excel.XlSheetType.xlWorksheet);
sheet.Name = dt.TableName;
string range = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);
sheet.get_Range(range, Type.Missing).Value2 = data;
((Excel.Range)sheet.Rows[1, Type.Missing]).Font.Bold = true;
}
workbook.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
excel.Quit();
KillSpecialExcel(excel);
excel = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
static void KillSpecialExcel(Excel.Application app)
{
try
{
if (app != null)
{
int processId;
GetWindowThreadProcessId(new IntPtr(app.Hwnd), out processId);
System.Diagnostics.Process.GetProcessById(processId).Kill();
}
}
catch (Exception ex)
{
throw ex;
}
}
文件流
這種方法的效率明顯高于第一種,而且也不需要安裝Office,但是導出的xls文件并不符合Excel的格式標準,在打開生成的xls文件時會提示:The file you are trying to open is in a different format that specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file.
|
新聞熱點
疑難解答