| 1. 調(diào)用Excel的COM組件。在項目中打開Add Reference對話框,選擇COM欄,之后在COM列表中找到"Microsoft Excel 11.0 Object Library"(Office 2003),然后將其加入到項目的References中即可。Visual C#.NET會自動產(chǎn)生相應(yīng)的.NET組件文件,以后即可正常使用。
     2. 打開Excel表格Excel.Application excel = new Excel.Application(); //引用Excel對象
 Excel.Workbook book = excel.Application.Workbooks.Add(Missing.Value); //引用Excel工作簿
 excel.Visible = bVisible; //使Excel可視
 有時調(diào)用excel.Application.Workbooks.Add(Missing.Value)會遇到如下錯誤:Exception:
 Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))
 這是Excel自身的一個bug,當(dāng)本地系統(tǒng)環(huán)境被設(shè)置成非英文的,而Excel是英文的時候,就會出現(xiàn),需要臨時設(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;
     ------------------------   特別是第二點。好有用!           |