這次來介紹如何建立一個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 進程, 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
http://topic.csdn.net/t/20040905/14/3341800.html
沒有留言:
張貼留言