轉 C# 读取excel 二种方法

来源:互联网 发布:nginx 反向代理优化 编辑:程序博客网 时间:2024/04/28 02:55

一.

经常需要在数据库与Execl之间互导数据。net时代,ADO.NET可以使用使用Microsoft.Jet.OleDb访问访问Excel,网上已经有很多类似的资源,最典型也是最简单的可能如下:(asp.net环境)

// 连接字符串            
         string xlsPath
= Server.MapPath("~/app_data/somefile.xls"); // 绝对物理路径
         string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                        
"Extended Properties=Excel 8.0;" +
                        
"data source=" + xlsPath;
         // 查询语句
         string sql
= "SELECT * FROM [Sheet1$]";

         DataSet ds
= new DataSet();
         OleDbDataAdapter da = new OleDbDataAdapter(sql, connStr);
         da.Fill(ds);     // 填充DataSet        
        
         // 在这里对DataSet中的数据进行操作        

         // 输出,绑定数据
         GridView1.DataSource
= ds.Tables[0];
         GridView1.DataBind();

很简单吧?!一切就像操作数据库一样,只是需要注意的是:
1。数据提供程序使用Jet,同时需要指定Extended Properties 关键字设置 Excel 特定的属性,不同版本的Excel对应不同的属性值:
用于 Extended Properties 值的有效 Excel 版本。
对于 Microsoft Excel
8.0 (97)、9.0 (2000) 和 10.0 (2002) 工作簿,请使用 Excel 8.0

对于 Microsoft Excel
5.07.0 (95) 工作簿,请使用 Excel 5.0

对于 Microsoft Excel
4.0 工作簿,请使用 Excel 4.0

对于 Microsoft Excel
3.0 工作簿,请使用 Excel 3.0

二.

在工程中加入相关的Com组件

代码示例:

ExcelObj=new Excel.Application();

object missing=Type.Missing;

Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(

this.textBoxExcelName.Text, missing, missing, missing,

missing, missing, missing, missing, missing, missing, missing,

missing,missing);

Excel.Sheets sheets = theWorkbook.Worksheets;

Excel.Worksheet datasheet=null;

foreach(Excel.Worksheet sheet in sheets)

{

if(sheet.Name==textBoxSheetName.Text)

{

datasheet=sheet;

break;

}

}

if(null==datasheet)

{

MessageBox.Show(this,"没有名称为"+textBoxSheetName+"的Sheet.");

return;

}

if(""==this.textBoxCellFrom.Text||""==this.textBoxCellTo.Text)

{

MessageBox.Show(this,"请输入编号起始单元格。");

return;

}

Excel.Range range=datasheet.get_Range(this.textBoxCellFrom.Text,this.textBoxCellTo.Text);

System.Array myvalues = (System.Array)(range.Cells.Value);//如果只有一个格(cellfrom==cellto)转成object即可.

string[] codes=new string[myvalues.Length];

int i=0;

for (i = 1; i <= myvalues.Length; i++)

{

if (myvalues.GetValue(i, 1) == null)

codes[i-1] = "";

else

codes[i-1] = (string)myvalues.GetValue(i, 1).ToString();

}

 
原创粉丝点击