最近想写个脚本来保存程序中的一些日志,最后选择用excel来保存,这里总结一下C#中使用office.excel的一些技巧吧!
首先在C#的工程中添加excel的dll。右键点击引用->添加新引用,然后找出Microsoft.Office.Interop. Excel的dll。
然后在using中添加:
using System.Reflection; using Excel=Microsoft.Office.Interop. Excel;
using System.Reflection是为了调用缺省方法Missing
接下来是具体的代码:
1 Excel.Application excelApp = new Excel.Application(); //Excel应用程序变量,初始化 2 Excel.Workbook excelDoc; //Excel文档变量 3 object OsPath,FilePath;//表格文件的保存地址 4 string FileName; 5 FileName="1.xls"; 6 OsPath =@"C:\Users\admin\Desktop\1.xls";//这里我定义了桌面的地址 7 FilePath=string.Format("{0}{1}",(string)OsPath,FileName);//为了自定义地址,加了一个地址拼接 8 Console.WriteLine(FilePath); //调试提示用的 9 object Nothing; 10 Nothing=Missing.Value;//给Nothing一个缺省的值 11 if (File.Exists((string)FilePath)) 12 { 13 14 Console.WriteLine("已经有了1.xls这个文件,文件路径为: {0}", FilePath); 15 Console.WriteLine(FilePath); 16 // excelDoc = excelApp.Workbooks.Open(path); //打开原来文件 17 } 18 else { 19 Console.WriteLine("还没有1.xls这个文件",FilePath); 20 } 21 excelDoc = excelApp.Workbooks.Add(Nothing);//Add()中的值不定义的时候给个缺省值就好了 22 Excel.Worksheet ws = (Excel.Worksheet)excelDoc.Sheets[1]; 23 Excel.Range i;//定义范围的变量 24 i = ws.get_Range("A1", "A2");//从“A1”到“A2”的位置 25 i.Value2 = "数据1"; 26 //WdSaveFormat为Excel文档的保存格式 27 object format = Excel.XlFileFormat.xlWorkbookDefault; 28 //将excelDoc文档对象的内容保存为XLSX文档 29 excelDoc.SaveAs(FilePath, format, Nothing, Nothing, Nothing, Nothing, Excel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing); 30 excelDoc.Close(Nothing, Nothing, Nothing); 31 //关闭excelApp组件对象 32 excelApp.Quit(); 33 Console.WriteLine("创建完毕");
喝水不忘挖井人,参考的博文地址:
http://hejianlong.123.blog.163.com/blog/static/26715839200932113312156/