1. 調(diào)用Excel的COM組件。
在項(xiàng)目中打開Add Reference對(duì)話框,選擇COM欄,之后在COM列表中找到"Microsoft Excel 11.0 Object Library"(Office 2003),然后將其加入到項(xiàng)目的References中即可。Visual C#.NET會(huì)自動(dòng)產(chǎn)生相應(yīng)的.NET組件文件,以后即可正常使用。
2. 打開Excel表格
Excel.Application excel = new Excel.Application(); //引用Excel對(duì)象
Excel.Workbook book = excel.Application.Workbooks.Add(Missing.Value); //引用Excel工作簿
excel.Visible = bVisible; //使Excel可視
有時(shí)調(diào)用excel.Application.Workbooks.Add(Missing.Value)會(huì)遇到如下錯(cuò)誤:
Exception:
Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))
這是Excel自身的一個(gè)bug,當(dāng)本地系統(tǒng)環(huán)境被設(shè)置成非英文的,而Excel是英文的時(shí)候,就會(huì)出現(xiàn),需要臨時(shí)設(shè)定英文環(huán)境,代碼如下:
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
3. 往Excel表格中插入數(shù)據(jù)
Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets["Sheet1"]; // 選中當(dāng)前新建Sheet(一般為Sheet1)
有兩種插入方法
a. 逐格插入數(shù)據(jù)
sheet.Cells[iRow, iCol] = value; // 左上角第一格的坐標(biāo)是[1, 1]
b. 按塊插入數(shù)據(jù)
object[,] objVal = new object[Height, Length];
// 設(shè)置數(shù)據(jù)塊
Excel.Range range = sheet.get_Range(sheet.Cells[iRow, iCol], sheet.Cells[iRow + Height, iCol + Length])
range.Value2 = objVal;
4. 清理內(nèi)存和恢復(fù)環(huán)境
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;
------------------------
特別是第二點(diǎn)。好有用!
聯(lián)系客服