码迷,mamicode.com
首页 > Windows程序 > 详细

C#对Excel文件模板的完全读取

时间:2015-01-23 11:17:19      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:源码   c#   excel   公式   样式   

针对“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();
        }


C#对Excel文件模板的完全读取

标签:源码   c#   excel   公式   样式   

原文地址:http://blog.csdn.net/ling1510/article/details/43052273

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!