C # write in an Excel template,
This is often the case in the program. Write operations are performed based on a specified template. Today, let's talk about how to perform such operations.
Add reference: Microsoft. Office. Interop. Excel. dll [Microsoft. Office. Interop. Excel. dll] namespace: using Excel = Microsoft. Office. Interop. Excel;
Namespace: using System. Reflection; namespace: using System. Diagnostics;
The Code is as follows:
// Specify the template path, % \ bin \ Debug. The relative path string str = System is recommended. windows. forms. application. startupPath; // create an Excel file. application excel_template = new Excel. application (); excel_template.UserControl = true; // create a workbook and add it to the template Excel. workbook workBook = excel_template.Workbooks.Add (@ str + "\ Template.xlsx"); // Try catch statements to catch exceptions, if you do not know, you can ignore try {// 3.3 and save the exported Excel report to the specified path for viewing. // Missing is in the System. Reflection namespace. // Select the Save path string savaPath = ""; SaveFileDialog opd = new SaveFileDialog (); // The SaveFileDialog method under System. Windows. Forms. You can select a path in the pop-up dialog box. Opd. filter = @ "Excel file (*. xls ,*. xlsx ,*. xlsm) | *. xls ;*. xlsx ;*. xlsm "; // select the storage type opd. filterIndex = 1; opd. fileName = "\ test table" + DateTime. now. toString ("yyyy_MM_dd_HHmmss") + ". xlsx "; // specifies the file name and type opd. restoreDirectory = true; if (opd. showDialog () = DialogResult. OK) {savaPath = opd. fileName;} workBook. saveAs (savaPath, Missing. value, Missing. value, Missing. value, Missing. value, Missing. value, Microsoft. offic E. interop. excel. xlSaveAsAccessMode. xlNoChange, Missing. value, Missing. value, Missing. value, Missing. value, Missing. value); // save // close the Excel Object // display excel excel_template.Visible = true;} catch {XtraMessageBox. show ("Incorrect path selection! "," Error ", MessageBoxButtons. OK, MessageBoxIcon. error);} // write excel_template.Cells [1, 1] = string. format ("test table"); // the content in the cell is the excel position excel_template.Cells [2, 4] = string. format ("successfully written ");