读取Excel表格中数据原型

时间:2023-03-08 16:04:32
读取Excel表格中数据原型

写下这篇博客来记录自己的工作,这部分功能是读取Excel表格中的数据,并通过c#中的datagridview控件将读取的数据显示出来。为了方便用户,我设计了一个read按钮,用户点击这个按钮,会弹出打开文件的窗口,选择想要打开的文件后,datagridview中会显示读取的表格数据。

程序运行截图如下:

读取Excel表格中数据原型

读取Excel表格中数据原型

读取Excel表格中数据原型

主要代码如下:

首先引用要System.Data.OleDb;

using System.Data.OleDb;

点击read按钮弹出打开文件的窗口:

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.Filter = "表格(*.xls)|*.xls|所有文件(*.*)|*.*";
if (openfile.FilterIndex == && openfile.ShowDialog() == DialogResult.OK)
ExcelToDS(openfile.FileName);
}

需要在Designer.cs文件中添加最下面的一行代码:

// button1
//
this.button1.Location = new System.Drawing.Point(, );
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(, );
this.button1.TabIndex = ;
this.button1.Text = "read";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//

读取数据显示在datagrid中:

 public DataSet ExcelToDS(string path)
{
//源的定义
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + @path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);//连接数据源
conn.Open();
//Sql语句
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);//适配到数据源
ds = new DataSet();//定义存放的数据表
myCommand.Fill(ds, "table1");
dataGridView1.DataSource = ds.Tables["table1"];
return ds; }

很简单的代码,但是问题就出在连接字符串上面,后面一定要加上Extended Properties='Excel 8.0;

一切就像操作数据库一样,只是需要注意的是:数据提供程序使用Jet,同时需要指定Extended Properties 关键字设置 Excel 特定的属性。

不同版本的Excel对应不同的属性值:

对于 Microsoft Excel 8.0 (97)、9.0 (2000) 和 10.0 (2002) 工作簿,请使用 Excel 8.0;

对于 Microsoft Excel 5.0 和 7.0 (95) 工作簿,请使用 Excel 5.0;

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

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