C# Generate Excel 檔案
係Project上 "Add Reference" -> "Microsoft.Office.Interop.Excel (Version 14.0.0.0)"
係Application Form上加 Microsoft.Office.Interop.Excel 既Library
C# Generate Excel 檔案 |
using Excel = Microsoft.Office.Interop.Excel; private void Create_Excel() { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; Object misValue = System.Reflection.Missing.Value; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); Generate_SpreedSheet(xlWorkSheet); xlWorkBook.SaveAs("C:\\result.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); ReleaseObject(xlWorkSheet); ReleaseObject(xlWorkBook); ReleaseObject(xlApp); MessageBox.Show("Excel file created , you can find the file C:\\result.xls"); } private void ReleaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; MessageBox.Show("Unable to release the Object " + ex.ToString()); } finally { GC.Collect(); } } private void Generate_SpreedSheet(Excel.Worksheet ws) { for(int o=1;o>0 && o<11;o++) { ws.Cells[o + 1, 1] = o; } for(int k=1;k>0 && k<11;k++) { ws.Cells[1, k + 1] = k; } for(int i=1;i>0 && i<11;i++) { for(int j=1;j>0 && j<11;j++) { ws.Cells[i + 1, j + 1] = (i * j); } } } |