最近想寫個腳本來保存程序中的一些日志,最后選擇用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/