[C#]将数据写入已存在的excel文件

测试如下(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         }

 

posted @ 2017-10-25 17:12  行走的DT  阅读(22002)  评论(3编辑  收藏  举报