ApplicationClass app;
Workbooks wbs;
Workbook wb;
Worksheets wss;
Worksheet ws;
Range rg1;
开始设计程序
app=new ApplicationClass();//打开Excel程序
wbs=app.Workbooks;
//wb=wbs.Add(Type.Missing);//添加一个新的Excel工作空间
wb=wbs.Open(xlsPath,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);//其中xlsPath代表要打开的路径
ws=(Worksheet)(wb.Worksheets.Add(wb.Workbooks.get_Item(1),Type.Missing,1,xlWorksheet));//添加一个Sheet表
ws.Name="SheetName";//设计Sheet表格的名字
关于退出Excel文件的处理
如果打开Excel文件:
wb.Save();
wb.Close(true,Type.Missing,Type.Missing);
wb=null;
app.Quit();
app=null
如果是新建的Workbook则:
wb.SaveAs(xlspath, XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wb.Close(true,Type.Missing,Type.Missing);
wb=null;
app.Quit();
app=null;
向Excel文件中写数据:
ws.Cell[1,1]="abc";
rg1=ws.get_Range("A1","B2");//获取Excel中A1--》B2之间的Cells共四个Cells,如果不明白,建议去理解一下什么是Range
object[] obj=new object[4]{"a","b","c","d"};
rg1.Value2=obj;//填充rg1空间,其中A1的值是a,A2的值是b,B1的值是C,B2的值是d
最后,C#处理Excel时需引入其命名空间
Using Microsoft.Office.Interop.Excel
该命名空间不是C#默认的命名空间,它存在于COM中!通过添加COM控件来实现。
Microsoft.Excel.12.0 Object Library
博客的目的是让自己记住一些东西!也是为了以后查找方便!呵呵!