摘要:[C#] - 建立Excel檔案
繼C#-讀取excel檔案&C#-如何使用oledb計算excel count後
這次來介紹如何建立一個excel檔案
首先,須先using下列幾個參考
using System.IO;//建立excel檔案需宣告
using Microsoft.Office.Interop.Excel;
using System.Reflection;
再來是code的部分
FileInfo fi=new FileInfo("Data.xls");
Microsoft.Office.Interop.Excel.Application xlapp=new Microsoft.Office.Interop.Excel.Application();
if (xlapp == null)
{
MessageBox.Show("請安裝office!!");
}
xlapp.Visible = false;//不顯示excel程式
Workbook wb=xlapp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws=(Worksheet)wb.Sheets[1];
ws.Name = "English";
Worksheet ws1 = (Worksheet)wb.Worksheets.Add(Type.Missing, ws, Type.Missing, Type.Missing);//建立一個新分頁
ws1.Name = "Japanese";
ws.Cells[1, 1]="word";
ws.Cells[1, 2] = "translate";
ws1.Cells[1, 1] = "word";
ws1.Cells[1, 2] = "translate";
ws.Cells[2, 1] = "Hello";
ws.Cells[2, 2] = "哈囉";
ws1.Cells[2, 1] = "こんにちは";
ws1.Cells[2, 2] = "你好";
if (ws == null||ws1==null)
{
MessageBox.Show("建立sheet失敗");
}
wb.SaveAs(@fi.DirectoryName+"\\Data.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wb.Close(false, Type.Missing, Type.Missing);
xlapp.Workbooks.Close();
xlapp.Quit();
//刪除 Windows工作管理員中的Excel.exe process,
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlapp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
儲存的格式Microsoft.Office.Interop.Excel.XlFileFormat
excel 2007=xlOpenXMLWorkbook(*.xlsx)
excel 2003=xlExcel8(*.xls)
參考出處:
http://www.rondebruin.nl/saveas.htm
http://jjnnykimo.pixnet.net/blog/post/24806313
http://msdn.microsoft.com/zh-tw/library/ms173186%28VS.80,classic%29.aspx