Although Ms does not recommend using automation to access Excel objects on the website, it is also possible to apply automation to intranets with only a small amount of access.
To use Excel Automation, you must first Add a reference for Microsoft. Office. InterOP. Excel. In the Add reference window of the project, find "Microsoft Excel 12.0 object" (Excel 2007, Microsoft Excel 2003 object "). After a reference is added, the following items appear in the <assemblies> section of Web. config:
<!-- Excel 2007 --><add assembly="Microsoft.Office.Interop.Excel, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C"/><!-- Excel 2003 --><add assembly="Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"/>
Now you can use the Excel Automation Object in Microsoft. Office. InterOP. Excel namespace in the program. Add the Excel namespace as follows:
using Excel = Microsoft.Office.Interop.Excel;
Create an Excel application using the following methods:
Excel.Application app = new Excel.Application();....
Open the Excel table:
Excel. workbook myWorkbook = app. open ("MyExcelBook.xlsx", Type. missing, true, // Open Type in read-only mode. missing, Type. missing, Type. missing, Type. missing, Type. missing, Type. missing, false, false, Type. missing, false, Type. missing, Type. missing );
Get worksheet set:
Excel.Sheets mySheets = myWorkbook.Sheets;for ( int i = 1; i <= mySheets.count; i++ ){ ...... Excel.Sheet mySheet = (Excel.Sheet)mySheets.get_Item(i); ......}
After the work is completed, save the work:
// Directly save myWorkbook. save (); // Save another workbook. saveAs (filename, Type. missing, Type. missing, Type. missing, Type. missing, Type. missing, Excel. xlSaveAsAccessMode. xlNoChange, Type. missing, Type. missing, Type. missing, Type. missing, Type. missing );
Finally, close the Excel application:
app.Quit();