測試如下(xls/xlsx):
1 //將數據寫入已存在Excel 2 public static void writeExcel(string result, string filepath) 3 { 4 //1.創建Applicaton對象 5 Microsoft.Office.Interop.Excel.Application xApp = new 6 7 Microsoft.Office.Interop.Excel.Application(); 8 9 //2.得到workbook對象,打開已有的文件 10 Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks.Open(filepath, 11 Missing.Value, Missing.Value, Missing.Value, Missing.Value, 12 Missing.Value, Missing.Value, Missing.Value, Missing.Value, 13 Missing.Value, Missing.Value, Missing.Value, Missing.Value); 14 15 //3.指定要操作的Sheet 16 Microsoft.Office.Interop.Excel.Worksheet xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1]; 17 18 //在第一列的左邊插入一列 1:第一列 19 //xlShiftToRight:向右移動單元格 xlShiftDown:向下移動單元格 20 //Range Columns = (Range)xSheet.Columns[1, System.Type.Missing]; 21 //Columns.Insert(XlInsertShiftDirection.xlShiftToRight, Type.Missing); 22 23 //4.向相應對位置寫入相應的數據 24 xSheet.Cells[Column(列)][Row(行)] = result; 25 26 //5.保存保存WorkBook 27 xBook.Save(); 28 //6.從內存中關閉Excel對象 29 30 xSheet = null; 31 xBook.Close(); 32 xBook = null; 33 //關閉EXCEL的提示框 34 xApp.DisplayAlerts = false; 35 //Excel從內存中退出 36 xApp.Quit(); 37 xApp = null; 38 }
