2010年6月23日 星期三

ASP.NET (使用C#) 處理excel檔案

自動產生excel檔 並儲存到server
請先加入參考~
Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook oBook = (Microsoft.Office.Interop.Excel.Workbook)oExcel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet oSheet = oBook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
//Microsoft.Office.Interop.Excel.Range objExcel_RG = null;
object oMissing = System.Reflection.Missing.Value;
oBook = oExcel.ActiveWorkbook;
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oBook.Worksheets[1];
oSheet.Cells[1, 1] = "test";
if (System.IO.File.Exists(Server.MapPath("~\\E_mail\\attached\\abc.xls")) == true)
{
System.IO.File.Delete(Server.MapPath("~\\E_mail\\attached\\abc.xls"));
}
oBook.SaveAs(Server.MapPath("~\\E_mail\\attached\\abc.xls"), oMissing, oMissing, oMissing, oMissing, oMissing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, oMissing, oMissing, oMissing,
oMissing,oMissing);
oSheet = null;
oBook = null;
oExcel.Quit();
oExcel = null;
GC.Collect();
非不得以採用此方法 此方法有可能造成EXCEL PROCESS 無法自動刪除問題存在

沒有留言:

張貼留言