C # method 2 (code example) for writing data to excel ),
C # method 2 for writing data to excel (code example)
Using System. IO; using System. reflection; using Microsoft. office. interop. excel; // Method 2: only new files can be created, and public static void write2 () {string path = @ "D: \ Excel1.xlsx" cannot be written on the basis of the original file "; // Excel Application variable, initialize Application excelApp = new ApplicationClass (); // determines whether the File exists. if yes, delete if (File. exists (path) {File. delete (path);} // because the COM library is used, many variables need to replace Object Nothing = Missing with Nothing. value; // Excel document variable Workbook excelDoc = ex CelApp. workbooks. add (Nothing); // use the first Worksheet as the Worksheet ws = (Worksheet) excelDoc to insert data. sheets [1]; // declare an MSExcel. range variable r Range r; // the name of the first row field, for example, giving a1 day false data, in fact, the data is added to cell a2 // obtain Table a2 and assign a value // r = ws. get_Range ("A1"); // r. value2 = "data 1"; // obtain the table d5 to a2 and assign the value r = ws. get_Range ("d4", "a1"); r. value2 = "5.7"; // delete data in this range // r. delete (); // insert row and column cells in the range r. insert (); // WdSaveFormat is the Excel file storage format object format = XlFileFormat. XlWorkbookDefault; // Save the content of the excelDoc file object as the XLSX file excelDoc. saveAs (path, format, Nothing, XlSaveAsAccessMode. xlExclusive, Nothing, Nothing); // close the excelDoc file object excelDoc. close (Nothing, Nothing, Nothing); // Close the excelApp Component Object excelApp. quit (); Console. writeLine (path + "created! ");}