Add reference first
Right-click a project -- add reference -- COM -- Microsoft Excel 12.0 Object Library
Here, 12.0 is a 2007 database, that is, the excel document in xlsx format can be operated.
[Csharp]
Using MSExcel = Microsoft. Office. Interop. Excel; // This sentence is actually for later convenience, so you can save a lot of words
Using System. IO;
Using System. Reflection;
Class Program
{
Static void Main (string [] args (
{
String path; // file path
MSExcel. Application excelApp; // Excel Application
MSExcel. WorkBook excelDoc; // Excel document
Path = @ "c:/test.xlsx ";
ExcelApp = new MSExcel. ApplicationClass ();
If (File. Exists (path)
{
File. Delete (path );
}
Object nothing = Missing. Value;
ExcelDoc = excelApp. Workbooks. Add (nothing );
Object format = MSExcel. XlFileFormat. xlWorkbookDefault;
ExcelDoc. SaveAs (path, nothing,
MSExcel. XlSaveAsAccessMode. xlExclusive, nothing, nothing );
ExcelDoc. Close (nothing, nothing, nothing );
ExcelApp. Quit ();
}
}
Because I learned other people's code, this article was copied directly. The original code was a bit wrong. After I changed it, there was no problem.
From icyfox_bupt