這是通過微軟office導出excel文件,為什麼通過微軟的office導出呢,因為我開始用的是npoi office導出,它不支持一種格式(就是html格式的excel文件),但是office支持,所以,寫個博客,給大家分享,分享
思維方式:通過讀取文件的excel文件,再通過模版格式導出相應的格式
////// 導出excel /// /// 讀取文件路徑 /// 保存文件內容 public static void ReadFile(string readFileName, string saveFileName) { Microsoft.Office.Interop.Excel.WorkbookClass wbclass; WorkbookClass wkTemp; Worksheet ws; Worksheet wsTemp; Microsoft.Office.Interop.Excel.Application excelApp; DirectoryInfo di = new DirectoryInfo(readFileName); //遍歷文件夾 if (di.Exists) { foreach (FileInfo item in di.GetFiles("*.xls")) { excelApp = new Microsoft.Office.Interop.Excel.Application(); object objOpt = System.Reflection.Missing.Value; //item.FullName 讀取execl文件 wbclass = (WorkbookClass)excelApp.Workbooks.Open(item.FullName, objOpt, false, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt); ws = (Worksheet)wbclass.Worksheets.get_Item(1); //取得總記錄行數 (包括標題列) int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行數 //int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列數 Range rng1 = ws.Cells.get_Range("C1", "C" + rowsint); //rang Range rng2 = ws.Cells.get_Range("D1", "D" + rowsint); //rang Range rng3 = ws.Cells.get_Range("E1", "E" + rowsint); //rang Range rng4 = ws.Cells.get_Range("F1", "F" + rowsint); //rang object[,] CallType = (object[,])rng1.Value2; object[,] ActiveCall = (object[,])rng2.Value2; object[,] PassivityCall = (object[,])rng3.Value2; object[,] CallDate = (object[,])rng4.Value; //通過模版讀取 wkTemp = (WorkbookClass)excelApp.Workbooks.Open("D:\\Template.xls", objOpt, false, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt); wsTemp = (Worksheet)wkTemp.Worksheets.get_Item(1); Range rngD = (Range)wsTemp.Columns["D", Type.Missing];//設置單元格格式 Range rngE = (Range)wsTemp.Columns["E", Type.Missing];//設置單元格格式 rngD.NumberFormat = "yyyy-mm-dd hh:mm:ss"; rngE.NumberFormat = "hh:mm:ss"; //通過模版寫入信息excel文件 for (int i = 1; i < rowsint; i++) { wsTemp.Cells[i, 1] = CallType[i, 1].ToString(); wsTemp.Cells[i, 2] = ActiveCall[i, 1].ToString(); wsTemp.Cells[i, 3] = PassivityCall[i, 1].ToString(); wsTemp.Cells[i, 4] = PassivityCall[i, 1].ToString(); } wsTemp.SaveAs(saveFileName + "\\1.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); excelApp.Workbooks.Close();//關閉打開的文檔 否則學號會顯示科學計數法。 excelApp.Quit(); } } }