针对“C#对Excel文件模板的完全读取”这样的一个题目,其实好像描述得不大对。在此再描述下:
如下代码主要是通过对一个Excel模板文件的读取,然后再想模板中填入对应的数据之后,另存为一个新的Excel文件。此文件完全符合原模板要求。(因为原Excel是带有很多样式和公式的,单独只提取原Excel的数值,是很难符合具体工作的需求的。)
源码:
需添加引用:using Excel = Microsoft.Office.Interop.Excel;
private void insertDataToExcel( string templateFilePath,ArrayList sourceData,string excelColumnName) //undo,no test { Excel.Application myExcelApp; Excel.Workbooks myExcelWorkbooks; Excel.Workbook myExcelWorkbook; object misValue = System.Reflection.Missing.Value; myExcelApp = new Excel.Application(); myExcelApp.Visible = false; myExcelWorkbooks = myExcelApp.Workbooks; String fileName = @"C:\AutomationReport\a1.xlsx"; String fileName2 = @"C:\AutomationReport\a4.xlsx"; // set this to your file you want //myExcelWorkbook = myExcelWorkbooks.OpenDatabase(fileName, misValue, misValue, misValue, misValue); myExcelWorkbook = myExcelWorkbooks.Open(fileName, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue); Excel.Worksheet myExcelWorksheet = (Excel.Worksheet)myExcelWorkbook.ActiveSheet; myExcelWorksheet.get_Range("A1", misValue).Formula = "3"; myExcelWorksheet.get_Range("A2", misValue).Formula = "2"; myExcelWorkbook.SaveAs(fileName2, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlNoChange, misValue, misValue, misValue, misValue, misValue); myExcelWorkbook.Close(); }