基于OleDb的Excel数据访问
比较以下两个连接字符串:
1)string connectionStr = string.Format("provider=Microsoft.Jet.OLEDB.4.0;data source={0};Extended Properties='Excel 8.0;HDR=NO;IMEX=1'", filePath);
2)string connectionStr = string.Format("provider=Microsoft.Jet.OLEDB.4.0;data source={0};Extended Properties=Excel 8.0;", filePath);
默认情况下,系统认为 Excel 数据源的第一行包含可用作字段名的列标题。如果不是这种情况,则必须
将该设置关闭,否则,第一行数据将会“消失”,而被用作字段名称。这可通过向连接字符串的扩展属性
添加可选的 HDR= 设置来完成。默认情况下(无需指定)是 HDR=Yes。如果没有列标题,则需要指定
HDR=No;提供程序将字段命名为 F1、F2 等等。因为扩展属性字符串现在包含了多个值,所以必须用引号
单独包起来(注意字符串中标为红色的部分)。
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace OledbExcel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string filePath = "Test.xls";
string connectionStr = string.Format("provider=Microsoft.Jet.OLEDB.4.0;data source={0};Extended Properties='Excel 8.0;HDR=NO;IMEX=1'", filePath);
string commandText = "select * from [Sheet1$]";
OleDbConnection con = new OleDbConnection(connectionStr);
OleDbCommand cmd = new OleDbCommand(commandText, con);
DataTable dt = new DataTable("ExcelInfo");
try
{
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(dt);
}
catch(Exception ex)
{
dt = null;
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
this.dataGridView.DataSource = dt;
this.dataGridView.Update();
}
}
}
参考:http://www.cnblogs.com/mczhu/archive/2008/07/17/1244978.html