2009-10-30 66 views
0

我想使用Microsoft.Office.Interop.Excel dll將數據寫入Excel工作表。我有一個代碼:如何使用Microsoft.Office.Interop.Excel dll以編程方式打開excel來編寫excel?

if (System.IO.File.Exists(strFileName)) 
{ 
    System.IO.File.SetAttributes(strFileName, FileAttributes.Normal); 
    System.IO.File.Delete(strFileName); 
} 

// Open an instance of excel. Create a new workbook. 
// A workbook by default has three sheets, so if you just want 
//a single one, delete sheet 2 and 3 

Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 
Excel._Workbook xlWB = (Excel._Workbook)xlApp.Workbooks.Add(Missing.Value); 

Excel._Worksheet xlSheet = (Excel._Worksheet)xlWB.Sheets[1]; 
((Excel._Worksheet)xlWB.Sheets[2]).Delete(); 
((Excel._Worksheet)xlWB.Sheets[2]).Delete(); 

xlSheet.Name = strSheetName; 

// Write a value into A1 
xlSheet.Cells[2, 1] = "Tags"; 
xlSheet.Cells[2, 2] = "Leak Test"; 
xlSheet.Cells[2, 3] = "FIR"; 
xlSheet.Cells[2, 4] = "SOP"; 

xlWB.SaveAs(strFileName, Missing.Value, Missing.Value, Missing.Value, 
Missing.Value,Missing.Value, 
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, 
Missing.Value, Missing.Value, Missing.Value, Missing.Value); 
xlApp.Quit(); 

// Release the COM object, set the Excel variables to Null, and tell the 
//Garbage Collector to do its thing 
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet); 
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWB); 
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp); 

xlSheet = null; 
xlWB = null; 
xlApp = null; 

現在我想打開現有的路徑& excel文件,然後把一些數據,我們提供姓名&那麼它將從程序保存到特定路徑上的Excel工作表。

請回復我的源代碼,如果有任何可以打開現有的Excel文件&,可以追加&另存爲另一個名稱。

問候, 吉里什

回答

1

如果您使用的是2007版本的Excel,我建議您使用ExcelPackage而不是它 - 它是OpenXML標準的實現,它比COM interop更快,更不麻煩,您可以在機器上運行它甚至沒有安裝Excel(Office),就像在您的Web服務器上一樣。

強烈建議 - 但僅限於Excel 2007及更高版本。

+0

你的意思是限於Excel XLSX,XLSM和XLST格式和更新的不是嗎? – 2010-09-10 04:26:43

+0

@匿名類型:是,2007和2010 OpenXML格式 - ExcelPackage支持這些格式。它不支持Excel 2003及更早版本使用的較舊的未公開的二進制XLS格式。 – 2010-09-10 04:52:38

3

ExcelPackage不再被維護。它似乎有一些錯誤。閱讀評論那裏,我發現http://epplus.codeplex.com/

它建立在ExcelPackage並繼承它的許可證(GPL),因此它可能不符合您的要求。