C#操作Excel文件的方法
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.IO;
namespace MyTest
{
 /// <summary>
 /// ReadExcel 的摘要说明。
 /// </summary>
 public class ReadExcel : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataGrid DataGrid1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!IsPostBack)
   {
    Response.Write( GetExcelFirstTableName( Server.MapPath("TestExcel.xls")));
    BindExcel();
   }
  }
  private void BindExcel()
  {
   string   strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("TestExcel.xls") +";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"" ;   
//对了还有一个HDR=Yes这个我说一下,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES.
///The possible settings of IMEX are: 
/// 0 is Export mode
    ///   1 is Import mode
   ///     2 is Linked mode (full update capabilities)
   //IMEX有3个值,
   //当IMEX=2 时,EXCEL文档中同时含有字符型和数字型时,
   //比如第C列有3个值,2个为数值型 123,1个为字符型 ABC,当导入时,
   //页面不报错了,但库里只显示数值型的123,而字符型的ABC则呈现为空值。
   //当IMEX=1时,无上述情况发生,库里可正确呈现 123 和 ABC.
   //我用的是1,在导入时,库里数字和字符类型的都导入了
    
   OleDbConnection conn = new OleDbConnection(strConn);   
   OleDbDataAdapter adp   = new OleDbDataAdapter("Select  * from [Sheet1$]",conn);     
   DataSet ds = new DataSet();     
   adp.Fill(ds,"Book1");   
   DataGrid1.DataSource = ds.Tables["Book1"].DefaultView;     
   DataGrid1.DataBind();     
}
  /// <summary>
  /// 获取EXXEL的表名
  /// </summary>
  /// <param name="excelFileName"></param>
  /// <returns></returns>
  private static string GetExcelFirstTableName(string excelFileName)
  {
   string tableName = null;
   if (File.Exists(excelFileName))
   {
    using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet."+
         "OLEDB.4.0;Extended Properties=\"Excel 8.0\";Data Source=" +  excelFileName))
    {
     conn.Open();
     DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
     for(int i=0;i<dt.Rows.Count;i++)
     {
      tableName+=dt.Rows[i][2].ToString().Trim()+";";
     }
    }
   }
   return tableName;
  }
得到表名 Sheet1$;Sheet2$;Sheet3$; 同时绑定了表内容到DATAGRID。

 我的故事
 我的故事
 栏目导航
栏目导航 全部文章
全部文章 随笔杂谈
随笔杂谈 最新评论
 最新评论 
							 统计信息
 统计信息
			 日记搜索
 日记搜索
			 其他信息
 其他信息
			


 
   
   



 
			 
				 
					
