1. 調用Excel的COM組件。
在項目中打開Add Reference對話框,選擇COM欄,之後在COM列表中找到"Microsoft Excel 11.0 Object Library"(Office 2003),然後將其加入到項目的References中即可。Visual C#.NET會自動產生相應的.NET組件文件,以後即可正常使用。
2. 打開Excel表格
Excel.Application excel = new Excel.Application(); //引用Excel對象
Excel.Workbook book = excel.Application.Workbooks.Add(Missing.Value); //引用Excel工作簿
excel.Visible = bVisible; //使Excel可視
有時調用excel.Application.Workbooks.Add(Missing.Value)會遇到如下錯誤:
Exception:
Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))
這是Excel自身的一個bug,當本地系統環境被設置成非英文的,而Excel是英文的時候,就會出現,需要臨時設定英文環境,代碼如下:
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
3. 往Excel表格中插入數據
Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets["Sheet1"]; // 選中當前新建Sheet(一般爲Sheet1)
有兩種插入方法
a. 逐格插入數據
sheet.Cells[iRow, iCol] = value; // 左上角第一格的座標是[1, 1]
b. 按塊插入數據
object[,] objVal = new object[Height, Length];
// 設置數據塊
Excel.Range range = sheet.get_Range(sheet.Cells[iRow, iCol], sheet.Cells[iRow + Height, iCol + Length])
range.Value2 = objVal;
4. 清理內存和恢復環境
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excel) > 0) ;
range = null;
sheet = null;
book = null;
excel = null;
GC.Collect();
System.Threading.Thread.CurrentThread.CurrentCulture = CurrentCI;
------------------------
特別是第二點。好有用!