Net操作Excel(终极方法NPOI)

来源:互联网 发布:淘宝怎么加入一淘 编辑:程序博客网 时间:2024/05/21 06:21

前言

Asp.net/C#操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使用NPOI能够帮助开发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等。NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。

方法

先去官网:http://npoi.codeplex.com/下载需要引入dll(可以选择.net2.0或者.net4.0的dll),然后在网站中添加引用。

Asp.Net导出代码:

NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("test_01");


// 第一列
NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
row.CreateCell(0).SetCellValue("第一列第一行");


// 第二列
NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(1);
row2.CreateCell(0).SetCellValue("第二列第一行");


// ...


// 写入到客户端  
System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
Response.BinaryWrite(ms.ToArray());
book = null;
ms.Close();
ms.Dispose();

Asp.Net导入代码:

HSSFWorkbook hssfworkbook;  
#region  
public DataTable ImportExcelFile(string filePath)  
{  
    #region//初始化信息  
    try  
    {  
        using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))  
        {  
            hssfworkbook = new HSSFWorkbook(file);  
        }  
    }  
    catch (Exception e)  
    {  
        throw e;  
    }  
    #endregion  
  
    NPOI.SS.UserModel.Sheet sheet = hssfworkbook.GetSheetAt(0);  
    System.Collections.IEnumerator rows = sheet.GetRowEnumerator();  
    DataTable dt = new DataTable();  
    for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)  
    {  
        dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());  
    }  
    while (rows.MoveNext())  
    {  
        HSSFRow row = (HSSFRow)rows.Current;  
        DataRow dr = dt.NewRow();  
        for (int i = 0; i < row.LastCellNum; i++)  
        {  
            NPOI.SS.UserModel.Cell cell = row.GetCell(i);  
            if (cell == null)  
            {  
                dr[i] = null;  
            }  
            else  
            {  
                dr[i] = cell.ToString();  
            }  
        }  
        dt.Rows.Add(dr);  
    }  
    return dt;  
}  
#endregion

 C#导出Excel:

public static void WriteExcel(DataTable dt, string filePath)
{
    if (!string.IsNullOrEmpty(filePath) && null != dt && dt.Rows.Count > 0)
    {
        NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
        NPOI.SS.UserModel.ISheet sheet = book.CreateSheet(dt.TableName);


        NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
        }
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + 1);
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                row2.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j]));
            }
        }
        // 写入到客户端  
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
        {
            book.Write(ms);
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                byte[] data = ms.ToArray();
                fs.Write(data, 0, data.Length);
                fs.Flush();
            }
            book = null;
        }
    }
}

文库资料:

Visual C#的 Excel 编程 
前言 
Excel 是微软公司办公自动化套件中的一个软件,他主要是用来处理电子表格。Excel 以其功能强大, 界面友好等受到了许多用户的欢迎。在办公的时候,正是由于 Excel 的这么多的优点,许多重要的数据, 往往以 Excel 电子表格的形式存储起来。这样就给程序员带来了一个问题,虽然 Excel 功能比较强大,但 毕竟不是数据库,在程序中处理数据库中的数据比其处理Excel表格中的数据容易许多。那么如何用Visual C#读取 Excel 表格中的数据?在以前用 Delphi 编程的时候,对于不同的用户,他们对于打印的需求是不 一样的,如果要使得程序中的打印功能适用于每一个用户,可以想象程序设计是十分复杂的。这时想到 Excel,由于 Excel 表格的功能强大,又由于几乎每一台机器都安装了它,如果把程序处理的结果放到 Excel 表格中,这样每一个用户就可以根据自己的需要在 Excel 中定制自己的打印。这样不仅使得程序设计简单, 而且又满足了诸多用户的要求,更加实用了。那么用 Visual C#如何调用 Excel,如何又把数据存放到 Excel 表格中?本文就来探讨一下上述问题的解决办法。 
一.程序设计及运行环境 
(1).微软视窗 2000 服务器版   (2)..Net Framework SDK Beta 2     (3).Microsoft Data Access Component 2.6 以上版本(MDAC2.6)     (4).Office 2000 套件  
二.Visual C#读取 Excel 表格中的数据: 
     本节将通过一个程序来介绍 Visual C#读取 Excel 表格中的数据,并把数据以 DataGrid 的形式显示 出来。 
(1).如何读取数据 
 
   其实读取 Excel 表格中的数据和读取数据库中的数据是非常类似的,因为在某种程度上 Excel 表格可 以看成是一张一张的数据表。其二者的主要区别在于所使用的数据引擎不一样。在本文的程序中,通过 下列代码实现读取 Excel 表格数据,具体如下: 
 
//创建一个数据链接 string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = c:\\sample.xls;Extended Properties=Excel 8.0" ; OleDbConnection myConn = new OleDbConnection ( strCon ) ; string strCom = " SELECT * FROM [Sheet1$] " ; myConn.Open ( ) ; 
file://打开数据链接,得到一个数据集 OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ; file://创建一个 DataSet 对象 myDataSet = new DataSet ( ) ; file://得到自己的 DataSet 对象 myCommand.Fill ( myDataSet , "[Sheet1$]" ) ; file://关闭此数据链接 myConn.Close ( ) ;  
 
怎么样读取 Excel 表格中的数据其实和读取数据库中的数据没有什么实质上的区别。 注释:这里读取的是 C 盘根目录下的"Sample.xls"文件。 
(2).用 DataGrid 来显示得到的数据集 
 
 在得到 DataSet 对象后,只需要通过下列二行代码,就可以把数据集用 DataGrid 显示出来了: 
 
 
DataGrid1.DataMember= "[Sheet1$]" ; DataGrid1.DataSource = myDataSet ;  
 
(3).用 Visual C#读取 Excel 表格,并用 DataGrid 显示出来的程序代码(Read.cs)和程序运行的界面 
掌握了上面二点,水到渠成就可以得到以下代码: using System ; using System.Drawing ; using System.Collections ; using System.ComponentModel ; using System.Windows.Forms ; using System.Data ; using System.Data.OleDb ; public class Form1 : Form { private Button button1 ; private System.Data.DataSet myDataSet ; private DataGrid DataGrid1 ; private System.ComponentModel.Container components = null ; 
 
public Form1 ( ) { file://初始化窗体中的各个组件 InitializeComponent ( ) ; 
file://打开数据链接,得到数据集 GetConnect ( ) ; } file://清除程序中使用过的资源 protected override void Dispose ( bool disposing ) { if ( disposing ) { if ( components != null )  { components.Dispose ( ) ; } } base.Dispose ( disposing ) ; } 
 
private void GetConnect ( ) { file://创建一个数据链接 string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = c:\\sample.xls;Extended Properties=Excel 8.0" ; OleDbConnection myConn = new OleDbConnection ( strCon ) ; string strCom = " SELECT * FROM [Sheet1$] " ; myConn.Open ( ) ; file://打开数据链接,得到一个数据集 OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom , myConn ) ; file://创建一个 DataSet 对象 myDataSet = new DataSet ( ) ; file://得到自己的 DataSet 对象 myCommand.Fill ( myDataSet , "[Sheet1$]" ) ; file://关闭此数据链接 myConn.Close ( ) ; } private void InitializeComponent ( ) { DataGrid1 = new DataGrid ( ) ; button1 = new Button ( ) ; SuspendLayout ( ) ; DataGrid1.Name = "DataGrid1"; DataGrid1.Size = new System.Drawing.Size ( 400 , 200 ) ; 
 
button1.Location = new System.Drawing.Point ( 124 , 240 ) ; button1.Name = "button1" ; button1.TabIndex = 1 ; 
button1.Text = "读取数据" ; button1.Size = new System.Drawing.Size (84 , 24 ) ; button1.Click += new System.EventHandler ( this.button1_Click ) ; 
 
this.AutoScaleBaseSize = new System.Drawing.Size ( 6 , 14 ) ; this.ClientSize = new System.Drawing.Size ( 400 , 280 ) ; this.Controls.Add ( button1 ) ; this.Controls.Add ( DataGrid1 ) ; this.Name = "Form1" ; this.Text = "读取 Excle 表格中的数据,并用 DataGrid 显示出来!" ; this.ResumeLayout ( false ) ; 
 
} private void button1_Click ( object sender , System.EventArgs e ) { DataGrid1.DataMember= "[Sheet1$]" ; DataGrid1.DataSource = myDataSet ; 
 
} static void Main ( )  { Application.Run ( new Form1 ( ) ) ; } } 
(4).总结 
 
以上只是读取了 Excel 表格中"Sheet1"中的数据,对于其他"Sheet"中的内容,可以参照读取"Sheet1" 中的程序,只作一点修改就可以了,譬如要读取"Sheet2"中的内容,只需要把"Read.cs"程序中的"Sheet1$" 改成"Sheet2$"就可以了。 
三.Visual C#调用 Excel 表格,并在 Excel 表格中存储数据: 
 在 Visual C#中调用 Excel 表格,并不像读取 Excel 表格中的数据那么容易了,因为在 Visual C# 中调用 Excel 表格要使用到 Excel 的 COM 组件。如果你安装 Office 套件在"C"盘,那么在"C:\Program Files\Microsoft Office\Office"可以找到这个 COM 组件"EXCEL9.OLB",在《Visual C#如何使用 Active X 组件》一文中,这些 COM 组件都是非受管代码的,要在 Visual C#中使用这些非受管代码的 COM 组件, 就必须把他们转换成受管代码的类库。所以在用 Visual C#调用 Excel 表格之前,必须完成从 COM 组件 的非受管代码到受管代码的类库的转换。 
(1).非受管代码 COM 组件转换成受管代码的类库 
 
首先把 COM 组件"EXCEL9.OLB"拷贝到 C 盘的根目录下,然后输入下列命令: tlbimp excel9.olb  这样在 C 盘的根目录下面就产生了三个 DLL 文件:"Excel.dll"、"Office.dll"、"VBIDE.dll"。在产 生了上面的三个文件后,这种转换就成功完成了。在下面的程序中,就可以利用这转换好的三个类 库编写和 Excel 表格相关的各种操作了。 注释: 1.在安装的程序中或许找不到 excel9.olb,可以利用下面的命令格式获取 dll 文件 Tlbimp execel.exe 也可以生成文件"Excel.dll","VBIDE.dll" 2.也可以使用 Visual Studio .net 2003 或其以上版本添加引用找到 Excel.exe 文件,会自动转化为 excel.dll 文件,然后在程序中添加包含即可 例如:using Excel; 请根据包的不同情况添加 
(2).Visual C#打开 Excel 表格: 
在"Excel.dll"中定义了一个命名空间"Excel",在差命名空间中封装了一个类"Application",这个类和 启动 Excel 表格有非常重要的关系,在 Visual C#中,只需要下列三行代码就可以完成打开 Excel 表格的 工作,具体如下: Excel.Application excel = new Excel.ApplicationClass ( ) ; excel.Application.Workbooks.Add ( true ) ; excel.Visible = true ;    但此时的 Excel 表格是一个空的表格,没有任何内容,下面就来介绍如何往 Excel 表格中输入数据。
 
(3).往 Excel 表格中输入数据: 
在命名空间"Excel"中,还定义了一个类"Cell",这个类所代表的就是 Excel 表格中的一个下单元。通 过给差"Cell"赋值,从而实现往 Excel 表格中输入相应的数据,下列代码功能是打开 Excel 表格,并且往 表格输入一些数据。 
 
Excel.Application excel = new Excel.ApplicationClass( ) ; excel.Application.Workbooks.Add ( true ) ; excel.Cells[ 1 , 1 ] = "第一行第一列" ;  excel.Cells[ 1 , 2 ] = "第一行第二列" ;  excel.Cells[ 2 , 1 ] = "第二行第一列" ;  excel.Cells[ 2 , 2 ] = "第二行第二列" ;  excel.Cells[ 3 , 1 ] = "第三行第一列" ;  excel.Cells[ 3 , 2 ] = "第三行第二列" ;  excel.Visible = true ;  
(4). Visual C#调用 Excel 表格,并在 Excel 表格中存储数据的程序代码(Excel.cs): 
   了解了上面的这些知识,得到完成上述功能的程序代码就显得比较容易了,具体如下: 
 
 
using System ; using System.Drawing ; using System.Collections ; using System.ComponentModel ; using System.Windows.Forms ; using System.Data ; using System.Data.SqlClient ; public class Form1 : Form { private Button button1 ; private System.ComponentModel.Container components = null ; public Form1 ( ) { file://初始化窗体中的各个组件 InitializeComponent ( ) ; } file://清除程序中使用的各个资源 protected override void Dispose ( bool disposing ) { if ( disposing ) { if ( components != null )  { components.Dispose ( ) ; } } base.Dispose( disposing ) ; } private void InitializeComponent ( ) { button1 = new Button ( ) ; SuspendLayout ( ) ; button1.Location = new System.Drawing.Point ( 32 , 72 ) ; button1.Name = "button1" ; button1.Size = new System.Drawing.Size ( 100 , 30 ) ; button1.TabIndex = 0 ; button1.Text = "调用 Excel 文件!" ; button1.Click += new System.EventHandler ( button1_Click ) ; 
 
AutoScaleBaseSize = new System.Drawing.Size ( 5 , 13 ) ; 
 
this.ClientSize = new System.Drawing.Size ( 292 , 273 ) ; this.Controls.Add ( button1 ) ; this.Name = "Form1" ; this.Text = "如何用 Visual C#调用 Excel 表格!" ; this.ResumeLayout ( false ) ; 
 
} static void Main ( )  { Application.Run ( new Form1 ( ) ) ; } private void button1_Click ( object sender , System.EventArgs e ) { Excel.Application excel = new Excel.Application ( ) ; excel.Application.Workbooks.Add ( true ) ; excel.Cells[ 1 , 1 ] = "第一行第一列" ;  excel.Cells[ 1 , 2 ] = "第一行第二列" ;  excel.Cells[ 2 , 1 ] = "第二行第一列" ;  excel.Cells[ 2 , 2 ] = "第二行第二列" ;  excel.Cells[ 3 , 1 ] = "第三行第一列" ;  excel.Cells[ 3 , 2 ] = "第三行第二列" ;  excel.Visible = true ;  } } 
(5).编译源程序和程序运行界面: 
 在经过了下列命令编译后: 
 
 
Csc.exe /r:system.dll /r:system.windows.forms.dll /r:system.drawing.dll /r:excel.dll /r:office.dll /r:vbide.dll excel.cs  
 
  就可以得到"Excel.exe",运行后界面如下 
 
 
四.Visual C#处理 Office 套件中的其他成员程序: 
 
本文虽然只介绍了 Visual C#在处理 Excel 表格中经常遇到的一些问题的解决方法,但其实对 Office 套件的其他成员也有很强的借鉴意义,譬如 Visual C#来处理 Word 文档,在调用 Word 文档的时候,必 须先完成 COM 组件从非受管代码到受管代码的转换,Word 的 COM 组件位"MSWORD9.OLB",经过转 换后也会产生三个 DLL 文件,但分别是"Word.dll"、"Office.dll"、"VBIDE.dll"。其实在 Visual C#中调用 Word,也非常容易。只需要把调用 Excel 表格中的代码换成调用 Word 的代码就可以了,具体如下: 
 
 
Word.Application word = new Word.Application ( ) ; word.Application.Visible = true ;  
 
  不信你试一下,看看是否达到你的要求。对于针对 Word 的其他的操作,总体来说和对 Excel 表格的 操作相类似。由于针对 Word 只是一个文档,程序对 Word 进行的操作是比较少的,所以就不一一介绍了。
 
 
五.总结: 
 
本文介绍 Visual C#来处理 Excel 表格的几种最常遇到的情况,虽然针对的只是 Excel 表格,但对其 他 Office 套件中的成员也具有十分的借鉴意义。 
 
 
程序示例及常见问题: 
前提:首先要把 Excel 加入到引用,加入方法见 :非受管代码 COM 组件转换成受管代码的类库 
示例 1:读取一个模板 excel 文件另存为另外一个 excel 文件 
using System; 
using Excel; 
namespace ExcelOperator.ClassExcel 

 /// <summary> 
 /// Example1 的摘要说明。 
 /// -----2006.08.31 Peter--------- 
 /// 读取一个模板excel文件另存为另外一个excel文件 
 /// 在做完操作之后立刻结束excel进程 
 /// --------   End    ------------ 
 /// </summary> 
 public class Example1 
 { 
  private DateTime beforeTime;      //Excel启动之前时间 
  private DateTime afterTime;                //Excel启动之后时间 
 
  private string OriginalPath; 
  private string CurrentPath; 
  public Example2(string CurrentPath,string OriginalPath) 
  { 
   this.OriginalPath=OriginalPath; 
   this.CurrentPath=CurrentPath; 
  } 
 
  public void OperatorExcel() 
  { 
   //GC.Collect(); 
    
   Excel.Application excel;      //声明excel对象 
 
   beforeTime = DateTime.Now;      //获取excel开始启动时间 
   excel=new Excel.ApplicationClass();    //创建对象实例,这时在系统进程中会多出一
个excel进程 
   afterTime = DateTime.Now;      //获取excel启动结束的时间 
   try  
   { 
    object missing=System.Reflection.Missing.Value;     //Missing 用于调
用带默认参数的方法。   
    object readOnly=true;            
    excel.Visible=false;           //是否显示excel文
档 
 
    //Open Original Excel File 
   
 excel.Application.Workbooks.Open(OriginalPath,missing,readOnly,missing,missing,missing,missing,missin
g,missing,missing,missing,missing,missing,missing,missing);    
     
    Excel.Workbook myBook=excel.Workbooks[1];        //Workbooks从1开始计数
的 
    Excel.Worksheet mySheet=(Excel.Worksheet)myBook.Worksheets[3]; //从1开始计数的 
 
    Excel.Range r=mySheet.get_Range(mySheet.Cells[1,17],mySheet.Cells[65231,17]);//获取矩形
选择框 
    r.NumberFormatLocal=XlColumnDataType.xlTextFormat ;        //设置
该矩形框的文本格式 
    
 
    //Save As  Original Excel File To CurrentPath 
   
 mySheet.SaveAs(CurrentPath,missing,missing,missing,missing,missing,missing,missing,missing,missing); 
    
 
    //释放Excel对象,但在Asp.net Web程序中只有转向另一个页面的时候进程才结束 
    //可以考虑使用KillExcelProcess()杀掉进程 
    //ReleaseComObject 方法递减运行库可调用包装的引用计数。详细信息见MSDN 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(r); 
 
    myBook.Close(null,null,null); 
    excel.Workbooks.Close(); 
    r=null; 
    mySheet=null; 
    myBook=null; 
    missing=null; 
    readOnly=null; 
    excel.Quit(); 
    excel=null;   
   } 
   catch 
   { 
    KillExcelProcess();   //杀掉进程 
   } 
   finally 
   { 
    //可以把KillExcelProcess();放在该处从而杀掉Excel的进程 
   } 
  } 
  private void KillExcelProcess() 
  { 
   System.Diagnostics.Process[] myProcesses; 
   DateTime startTime; 
   myProcesses = System.Diagnostics.Process.GetProcessesByName("Excel"); 
 
   //得不到Excel进程ID,暂时只能判断进程启动时间 
   foreach(System.Diagnostics.Process myProcess in myProcesses) 
   { 
    startTime = myProcess.StartTime; 
 
    if(startTime > beforeTime && startTime < afterTime) 
    { 
     myProcess.Kill(); 
    } 
   } 
  } 
 } 

示例 2:创建一个空文档,朝某一单元格写入值,并保存该 excel 文档 
using System; 
using Excel; 
 
namespace ExcelOperator.ClassExcel 

 /// <summary> 
 /// Example1 的摘要说明。 
 /// -----2006.08.31 Peter--------- 
 /// 创建一个空文档,朝某一单元格写入值,并保存该excel文档 
 /// 做完操作之后立刻关闭excel进程 
 /// --------  End  --------------- 
 /// </summary> 
 public class Example2 
 { 
  private DateTime beforeTime;      //Excel启动之前时间 
  private DateTime afterTime;                //Excel启动之后时间 
  private string path; 
  
  public Example2(string path) 
  { 
   this.path=path; 
  } 
 
  public void OperatorExcel() 
  { 
   //GC.Collect(); 
    
   Excel.Application excel;      //声明excel对象 
 
   beforeTime = DateTime.Now;      //获取excel开始启动时间 
   excel=new Excel.ApplicationClass();    //创建对象实例,这时在系统进程中会多出一
个excel进程 
   afterTime = DateTime.Now;      //获取excel启动结束的时间 
   try  
   { 
    object missing=System.Reflection.Missing.Value;     //Missing 用于调
用带默认参数的方法。         
    excel.Visible=false;           //是否显示excel文
档 
    //Open Original Excel File 
    excel.Application.Workbooks.Add(true);   
     
    _Workbook  myBook;       //声明Workbook类 
    _Worksheet mySheet;      //声明Worksheet类 
     
    myBook=excel.Workbooks[1];     //获取excel程序的工作簿 
    mySheet=(Worksheet)myBook.ActiveSheet;  //获取Workbook的活动工作表(最上层的工作
表)。 
    mySheet.Cells[1,1]="朝[A,1]单元格写入值"; 
    
    //Save As  Path 
   
 mySheet.SaveAs(path,missing,missing,missing,missing,missing,missing,missing,missing,missing); 
    
    //释放Excel对象,但在Asp.net Web程序中只有转向另一个页面的时候进程才结束 
    //可以考虑使用KillExcelProcess()杀掉进程 
    //ReleaseComObject 方法递减运行库可调用包装的引用计数。详细信息见MSDN 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 
 
    myBook.Close(null,null,null); 
    excel.Workbooks.Close(); 
    mySheet=null; 
    myBook=null; 
    missing=null; 
    excel.Quit(); 
    excel=null;   
   } 
   catch 
   { 
    KillExcelProcess();   //杀掉进程 
   } 
   finally 
   { 
    //可以把KillExcelProcess();放在该处从而杀掉Excel的进程 
    KillExcelProcess(); 
   } 
  } 
  private void KillExcelProcess() 
  { 
   System.Diagnostics.Process[] myProcesses; 
   DateTime startTime; 
   myProcesses = System.Diagnostics.Process.GetProcessesByName("Excel"); 
 
   //得不到Excel进程ID,暂时只能判断进程启动时间 
   foreach(System.Diagnostics.Process myProcess in myProcesses) 
   { 
    startTime = myProcess.StartTime; 
 
    if(startTime > beforeTime && startTime < afterTime) 
    { 
     myProcess.Kill(); 
    } 
   } 
  } 
 } 

示例 3:Excel 程序的工作簿(workbook)常用方法属性介绍 
更多的 workbook 的方法和属性: http://msdn2.microsoft.com/zh-CN/library/microsoft.office.tools.excel.workbook_members.aspx using System; 
using Excel; 
namespace ExcelOperator.ClassExcel 

 /// <summary> 
 /// Example1 的摘要说明。 
 /// -----2006.08.31 Peter--------- 
 /// Excel程序的工作簿(workbook)常用方法属性介绍 
 /// 在做完操作之后立刻结束excel进程,并保存excel文件 
 /// --------   End    ------------ 
 /// </summary> 
 public class Example3 
 { 
  private DateTime beforeTime;      //Excel启动之前时间 
  private DateTime afterTime;                //Excel启动之后时间 


 
  private string path; 
   
  public Example3(string path) 
  { 
   this.path=path; 
  } 
 
  public void OperatorExcel() 
  { 
   //GC.Collect(); 
    
   Excel.Application excel;      //声明excel对象 
 
   beforeTime = DateTime.Now;      //获取excel开始启动时间 
   excel=new Excel.ApplicationClass();    //创建对象实例,这时在系统进程中会多出一
个excel进程 
   afterTime = DateTime.Now;      //获取excel启动结束的时间 
   try  
   { 
    object missing=System.Reflection.Missing.Value;     //Missing 用于调
用带默认参数的方法。   
     
    excel.Visible=false;           //是否显示excel文
档 
    excel.Application.Workbooks.Add(true);   
     
      
    _Workbook  myBook;       //声明Workbook类 
    _Worksheet mySheet;       //声明Worksheet类 
    myBook=excel.Workbooks[1]; 
     
   
 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
 //+++++++++++++++++++     Workbook 常用方法和属性        +++++++++++++++++++++++++++++++++++ 
 
    myBook.Author="Peter";         //获取或设置工作簿的作者。 
    string myBookApplication=myBook.Application.ToString(); //获取表示工作簿创建者的 
Microsoft.Office.Interop.Excel.Application。 
    mySheet=(_Worksheet)myBook.ActiveSheet;       //获取活动工作表
(最上层的工作表)。 
    string myBookFullName=myBook.FullName.ToString();  //获取对象的名称,包括其磁盘路
径。 
    string myBookFileFormat=myBook.FileFormat.ToString(); //获取工作簿的文件格式和类型。 
    string myBookName=myBook.Name.ToString();    //获取工作簿的名称。 
 
 //其他详细属性见: 
 //  http://msdn2.microsoft.com/zh-CN/library/microsoft.office.tools.excel.workbook_members.aspx 
 //+++++++++++++++++++             End                        ++++++++++++++++++++++++++++++++++ 
 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
     
 
    //Save As  Original Excel File To CurrentPath 
   
 myBook.SaveAs(path,missing,missing,missing,missing,missing,XlSaveAsAccessMode.xlNoChange,missing,miss
ing,missing,missing,missing); 
 
    //释放Excel对象,但在Asp.net Web程序中只有转向另一个页面的时候进程才结束 
    //可以考虑使用KillExcelProcess()杀掉进程 
    //ReleaseComObject 方法递减运行库可调用包装的引用计数。详细信息见MSDN 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 
    
    myBook.Close(null,null,null); 
    excel.Workbooks.Close(); 
    mySheet=null; 
    myBook=null; 
    missing=null; 
    excel.Quit(); 
    excel=null;   
   } 
   catch 
   { 
    KillExcelProcess();   //杀掉进程 
   } 
   finally 
   { 
    //可以把KillExcelProcess();放在该处从而杀掉Excel的进程 
    KillExcelProcess(); 
   } 
  } 
  private void KillExcelProcess() 
  { 
   System.Diagnostics.Process[] myProcesses; 
   DateTime startTime; 
   myProcesses = System.Diagnostics.Process.GetProcessesByName("Excel"); 
 
   //得不到Excel进程ID,暂时只能判断进程启动时间 
   foreach(System.Diagnostics.Process myProcess in myProcesses) 
   { 
    startTime = myProcess.StartTime; 
 
    if(startTime > beforeTime && startTime < afterTime) 
    { 
     myProcess.Kill(); 
    } 
   } 
  } 
 } 

示例 4:在工作簿(workbook)中添加删除工作表(worksheet) 
using System; 
using Excel; 
namespace ExcelOperator.ClassExcel 

 /// <summary> 
 /// Example1 的摘要说明。 
 /// -----2006.08.31 Peter--------- 
 /// 工作表(worksheet)的添加和删除 
 /// 在做完操作之后立刻结束excel进程,并保存excel文件 
 /// --------   End    ------------ 
 /// </summary> 
 public class Example4 
 { 
  private DateTime beforeTime;      //Excel启动之前时间 
  private DateTime afterTime;                //Excel启动之后时间 
 
  private string path; 
   
  public Example4(string path) 
  { 
   this.path=path; 
  } 
 
  public void OperatorExcel() 
  { 
   //GC.Collect(); 
    
   Excel.Application excel;      //声明excel对象 


 
   beforeTime = DateTime.Now;      //获取excel开始启动时间 
   excel=new Excel.ApplicationClass();    //创建对象实例,这时在系统进程中会多出一
个excel进程 
   afterTime = DateTime.Now;      //获取excel启动结束的时间 
   try  
   { 
    object missing=System.Reflection.Missing.Value;     //Missing 用于调
用带默认参数的方法。   
     
    excel.Visible=false;           //是否显示excel文
档 
    excel.Application.Workbooks.Add(true);   
     
      
    _Workbook  myBook;       //声明Workbook类 
    _Worksheet mySheet;       //声明Worksheet类 
    myBook=excel.Workbooks[1]; 
     
   
    object mySheetEnd=(int)myBook.Sheets.Count; 
 
    //在第一个位置添加工作表 
    mySheet=(_Worksheet)myBook.Sheets.Add(missing,missing,missing,missing); 
    mySheet.Name="MySheetFirst"; 
     
    //在第一个位置后面添家一个工作表 
    _Worksheet 
mySheet1=(_Worksheet)myBook.Sheets.Add(missing,myBook.Sheets[1],missing,missing); 
     mySheet1.Name="MySheetEnd"; 
    //Add 方法允许您将一个新表添加到工作簿中的表集合中,并且可以接受四个可选参数,这些参数可
以指明表的位置、要添加的表数和表的类型(工作表、图表等):  
     
    //删除第三个工作表 
    ((Worksheet)myBook.Sheets[3]).Delete(); 
  
     
    //Save As  Original Excel File To CurrentPath 
   
 myBook.SaveAs(path,missing,missing,missing,missing,missing,XlSaveAsAccessMode.xlNoChange,missing,miss
ing,missing,missing,missing); 
 
    //释放Excel对象,但在Asp.net Web程序中只有转向另一个页面的时候进程才结束 
    //可以考虑使用KillExcelProcess()杀掉进程 
    //ReleaseComObject 方法递减运行库可调用包装的引用计数。详细信息见MSDN 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheetEnd); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet1); 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 
    
    myBook.Close(null,null,null); 
    excel.Workbooks.Close(); 
    mySheet=null; 
    mySheetEnd=null; 
    mySheet1=null; 
    //mySheetAfter=null; 
    myBook=null; 
    missing=null; 
    excel.Quit(); 
    excel=null;   
   } 
   catch 
   { 
    KillExcelProcess();   //杀掉进程 
   } 
   finally 
   { 
    //可以把KillExcelProcess();放在该处从而杀掉Excel的进程 
    KillExcelProcess(); 
   } 
  } 
  private void KillExcelProcess() 
  { 
   System.Diagnostics.Process[] myProcesses; 
   DateTime startTime; 
   myProcesses = System.Diagnostics.Process.GetProcessesByName("Excel"); 
 
   //得不到Excel进程ID,暂时只能判断进程启动时间 
   foreach(System.Diagnostics.Process myProcess in myProcesses) 
   { 
    startTime = myProcess.StartTime; 
 
    if(startTime > beforeTime && startTime < afterTime) 
    { 
     myProcess.Kill(); 
    } 
   } 
  } 
 } 

示例 5:工作表(worksheet)和 Range 对象的操作 
using System; using Excel; namespace ExcelOperator.ClassExcel {  /// <summary>  /// Example1 的摘要说明。  /// -----2006.08.31 Peter---------  /// 工作表(worksheet)的操作  /// 在做完操作之后立刻结束excel进程,并保存excel文件  /// --------   End    ------------  /// </summary>  public class Example5  {   private DateTime beforeTime;      //Excel启动之前时间   private DateTime afterTime;                //Excel启动之后时间 
 
  private string path;      public Example5(string path)   {    this.path=path;   } 
 
  public void OperatorExcel()   {    //GC.Collect();        Excel.Application excel;      //声明excel对象 
 
   beforeTime = DateTime.Now;      //获取excel开始启动时间    excel=new Excel.ApplicationClass();    //创建对象实例,这时在系统进程中 会多出一个excel进程    afterTime = DateTime.Now;      //获取excel启动结束的时间    try     {     object missing=System.Reflection.Missing.Value;     //Missing 用于调用带默认参数的方法。        
    excel.Visible=false;           //是否显示excel 文档     excel.Application.Workbooks.Add(true);                  _Workbook  myBook;       //声明Workbook类     _Worksheet mySheet;       //声明Worksheet类     myBook=excel.Workbooks[1];     mySheet=(Worksheet)myBook.ActiveSheet;        mySheet.Cells[1,1]=123;      //给某一单元格赋值     Excel.Range r=excel.ActiveCell;     Excel.Range r1=mySheet.get_Range(mySheet.Cells[1,1],mySheet.Cells[1,4]);     //Excel.Range r1=mySheet.get_Range("A1:A10",missing);     Excel.Range r2= (Excel.Range)mySheet.Cells[2, 1];     Excel.Range r3= (Excel.Range)mySheet.Rows[1,Type.Missing];     Excel.Range r4= (Excel.Range)mySheet.Columns[Type.Missing,5];          r.Font.Bold=true;           //设置字体     r.Font.Color=System.Drawing.Color.Yellow.ToArgb();   //设置字体颜色  
 
    r.Cells.Interior.Color=System.Drawing.Color.Red.ToArgb(); //设置背景颜色 
 
    r.Borders.Color=55;           //设置边框     r.Borders.Weight=Excel.XlBorderWeight.xlThick;          r.AddComment("这是第一个单元格");           //增加批注     //r.ClearContents() ;          //保留格式  清 除内容          r.HorizontalAlignment=Excel.XlHAlign.xlHAlignCenter;    //设置水平对齐方式     r.VerticalAlignment=Excel.XlVAlign.xlVAlignBottom;     //设置垂直对齐方式          r1.Merge(true);              //合并单元格          mySheet.Cells[2, 1]=1;         //使用函数     mySheet.Cells[3, 1]=1;     mySheet.Cells[4,1]="=sum(A2:A3)";          r3.NumberFormat=XlColumnDataType.xlDMYFormat;   //设置文本格式         //Save As  Original Excel File To CurrentPath     myBook.SaveAs(path,missing,missing,missing,missing,missing,XlSaveAsAccessMode.xlNoChange,mi
ssing,missing,missing,missing,missing); 
 
    //释放Excel对象,但在Asp.net Web程序中只有转向另一个页面的时候进程才结束     //可以考虑使用KillExcelProcess()杀掉进程     //ReleaseComObject 方法递减运行库可调用包装的引用计数。详细信息见MSDN     System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook);     System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet);     System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);     System.Runtime.InteropServices.Marshal.ReleaseComObject(r);     System.Runtime.InteropServices.Marshal.ReleaseComObject(r1);     System.Runtime.InteropServices.Marshal.ReleaseComObject(r2);     System.Runtime.InteropServices.Marshal.ReleaseComObject(r3);     System.Runtime.InteropServices.Marshal.ReleaseComObject(r4);     myBook.Close(null,null,null);     r=null;     r1=null;     r2=null;     r3=null;     r4=null;     excel.Workbooks.Close();     mySheet=null;     myBook=null;     missing=null;     excel.Quit();     excel=null;      }    catch    {     KillExcelProcess();   //杀掉进程    }    finally    {     //可以把KillExcelProcess();放在该处从而杀掉Excel的进程     KillExcelProcess();    }   }   private void KillExcelProcess()   {    System.Diagnostics.Process[] myProcesses;    DateTime startTime;    myProcesses = System.Diagnostics.Process.GetProcessesByName("Excel"); 
 
   //得不到Excel进程ID,暂时只能判断进程启动时间    foreach(System.Diagnostics.Process myProcess in myProcesses) 
   {     startTime = myProcess.StartTime; 
 
    if(startTime > beforeTime && startTime < afterTime)     {      myProcess.Kill();     }    }   }  } } 
示例 6:读取数据填充 DataSet 
using System; 
 
namespace ExcelOperator.ClassExcel {  /// <summary>  /// Example6 的摘要说明  /// ------2006 09 03 Peter------  ///读取数据填充DataSet  /// </summary>  public class Example6  {   string filePath;   public Example6(string path)   {    //    // TODO: 在此处添加构造函数逻辑    //    filePath=path;      }   public System.Data.DataSet OperatorExcel()   {        System.Data.OleDb.OleDbConnection oleCon= new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;data source="+filePath+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'");            System.Data.OleDb.OleDbDataAdapter oleAdp=new System.Data.OleDb.OleDbDataAdapter("select top 10 F5,F17 from [old3$]",oleCon);    System.Data.DataSet ds=new System.Data.DataSet();    oleAdp.Fill(ds); 
   return ds;   }  } } 
 
 
 
1.System.UnauthorizedAccessException: 拒绝访问。 
当试图在 ASP.NET 里面使用 COM 对象的时候,常常出现这个异常。 可以尝试在 web.config 里面添加以下一行以解决这个问题 <identity impersonate="true" userName=" " password=" "/> 
2.Excel 返回 DataSet 时读取此列部分数据为 Null 的解决方法 
问题:Excel 某列为时间格式,但实际存储数据的时候可能写入的是字符串文本。用上述方法返回 DataSet 中无法读取此列文本数据。 
解决方案:很简单, 
string strConn= "Provider=Microsoft.Jet.OleDb.4.0;" + "data source="+Path+ ";Extended Properties='Excel 
8.0;HDR=Yes;IMEX=1'"; 
"HDR=Yes;" indicates that the first row contains columnnames, not data "IMEX=1;" tells the driver to always read "intermixed" data columns as text 
3.安全性异常  
说明: 应用程序试图执行安全策略不允许的操作。要授予此应用程序所需的权限,请与系统管理员联系,或在配置文件中更改该 应用程序的信任级别。  异常详细信息: System.Security.SecurityException: 不允许所请求的注册表访问权。 权限问题,解决掉权限就可以了。 解决方法列举两个:   (1) <identity impersonate="true" userName="" password=""/>  userName 设置为管理员用户 (2) <identity impersonate="true" userName="" password=""/> 把 IUSER_MachineName 的权限设置为 power user or administrator user 
 
附录 
microsoft.office.tools.excel 命名空间: http://msdn2.microsoft.com/zh-CN/library/microsoft.office.tools.excel.aspx Worksheet 成员  http://msdn2.microsoft.com/zh-CN/library/microsoft.office.tools.excel.worksheet_members.aspx 开发 Office Developer 应用程序 http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/modcore/html/deovrtherangeproperty.asp 

0 0
原创粉丝点击