首先需要引用命名空间
using System.IO; using System.Data.OleDb;
下面是程序代码
string fName;
private void readButton_Click(object sender, EventArgs e)
{
//用于获取excel文件名
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = "D:\\";
open.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
if (open.ShowDialog() == DialogResult.OK)
{
fName = open.FileName;
}
try
{
//连接字符串
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fName + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; // Office 07及以上版本 不能出现多余的空格 而且分号注意
//string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; //Office 07以下版本
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //得到所有sheet的名字
string firstSheetName = sheetsName.Rows[0][2].ToString(); //得到第一个sheet的名字
string sql = string.Format("SELECT * FROM [{0}]", firstSheetName); //查询字符串
//string sql = string.Format("SELECT * FROM [{0}] WHERE [日期] is not null", firstSheetName); //查询字符串
OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
DataSet set = new DataSet();
ada.Fill(set);
dataGridView1.DataSource = set.Tables[0];//将文件读取到datagridview中
}
}
catch (Exception)
{
}
}