private void btnDisplay_Click(object sender, EventArgs e)//上传控件
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = “所有文件(.)|.”;
if (openFile.ShowDialog() == DialogResult.OK)
{
FilePath = openFile.FileName;
}
else return;//如果没有选择或者其他 直接退出
DataTable dt= ImportExcelToDataTable2(FilePath);
dgvAuthor.DataSource = null;//展示数据到DatAGV控件
dgvAuthor.AutoGenerateColumns = false;
dgvAuthor.DataSource = dt;
}
public static DataTable ImportExcelToDataTable2(string path)
{
string conStr = string.Format(“Provider=Microsoft.ACE.OLEDB.12.0; Data source={0}; Extended Properties=Excel 12.0;”, path);
using (OleDbConnection conn = new OleDbConnection(conStr))
{
conn.Open();
//获取所有Sheet的相关信息
DataTable dtSheet = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
//获取第一个 Sheet的名称
string sheetName = dtSheet.Rows[0][“Table_Name”].ToString();
string sql = string.Format(“select * from [{0}]”, sheetName);
using (OleDbDataAdapter oda = new OleDbDataAdapter(sql, conn))
{
DataTable dt = new DataTable();
oda.Fill(dt);
return dt;
}
}
}
C#将Excel文件导入到DataTable并展示到DatAGV控件中
最新推荐文章于 2024-01-19 16:36:54 发布