C#打开excel文件
public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
{
//源的定义,如果第一行的数据是数据源,那么HDR=NO
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";
//Sql语句
//string strExcel = string.Format("select * from [{0}$]", strSheetName); 这是一种方法
string strExcel = "select * from [Sheet0$]";
//定义存放的数据表
DataSet ds = new DataSet();
//连接数据源
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
//适配到数据源
OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
adapter.Fill(ds, strSheetName);
conn.Close();
return ds.Tables[strSheetName];
}
//文件选择,判断文件是否存在,如果文件存在,调用方法解析excel,放入数据表中
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Title = "请选择文件";
fileDialog.Filter = "所有文件(*.*)|*.*";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string file = fileDialog.FileName;
if (File.Exists(@"D:\订单数据.xlsx"))
{
dataGridView1.DataSource = null; //每次打开清空内容
//DataTable dt = ReadExcelToTable(file);
DataTable dt = ExcelToDataTable(file, "Sheet0");
dataGridView1.DataSource = dt;
MessageBox.Show("已选择文件:" + file, "选择文件提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("无此文件");
}
}
}