当前位置:软件学习 > Excel >>

C#下操作EXCEL--新建EXCEL文件

首先要添加引用

右键点项目——添加引用——COM——Microsoft Excel 12.0 Object Library

这里说一下,12.0是2007的库,也就是可以操作xlsx格式的excel文档的

[csharp]
using MSExcel = Microsoft.Office.Interop.Excel; //这一句其实是为了后面使用方便,这样可以省去打很多字 
 
using System.IO; 
 
using System.Reflection; 
 
Class Program 
 

 
  static void Main(string[] args( 
 
  { 
 
    string path;  //文件路径 
 
    MSExcel.Application excelApp;  //Excel应用程序 
 
    MSExcel.WorkBook excelDoc;  //Excel文档 
 
    path = @"c:/test.xlsx"; 
 
    excelApp = new MSExcel.ApplicationClass(); 
 
    if(File.Exists(path) 
 
    { 
 
      File.Delete(path); 
 
    } 
 
    Object nothing = Missing.Value; 
 
    excelDoc = excelApp.Workbooks.Add(nothing); 
 
    Object format = MSExcel.XlFileFormat.xlWorkbookDefault; 
 
    excelDoc.SaveAs(path,nothing,nothing,nothing,nothing,nothing, 
 
          MSExcel.XlSaveAsAccessMode.xlExclusive,nothing,nothing,nothing,nothing,nothing); 
 
    excelDoc.Close(nothing,nothing,nothing); 
 
    excelApp.Quit(); 
 
  } 
 

因为主要是学习别人的代码,所以这条就直接复制了,原来的代码有点错误,我改了以后没有问题了。


摘自 icyfox_bupt的专栏
补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,