开发者

How to write excel by opening it programmatically with Microsoft.Office.Interop.Excel dll?

开发者 https://www.devze.com 2022-12-10 07:44 出处:网络
I want to use Microsoft.Office.Interop.Excel dll to write the data into excel sheet. I have a code: if (System.IO.File.Exists(strFileName))

I want to use Microsoft.Office.Interop.Excel dll to write the data into excel sheet. I have a code:

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

// Open an instance of excel. Creat开发者_StackOverflowe 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;

Now I want to open the existing excel file from the path & then put the some data into the excel sheet that we name provided & then it will be saved onto specific path from programmatically.

Please reply me the source if any that can open the existing excel file & that can be append & save with another name.

Regards, Girish


ExcelPackage is not maintained anymore. It seems to have a few bugs. Reading comment there, I've found http://epplus.codeplex.com/

It built upon ExcelPackage and inherit it licenses (GPL), so it may not suit your requirement.


If you're using the 2007 version of Excel, I would recommend using ExcelPackage instead - it's an implementation of the OpenXML standard, it's much faster and a lot less messy than COM interop, and you can run it on a machine that doesn't even have Excel (Office) installed, like on your web server.

Highly recommended - but limited to Excel 2007 and up.


Refer here for information.

0

精彩评论

暂无评论...
验证码 换一张
取 消