C#将Excel文件导入到DataTable并展示到DatAGV控件中

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;
}
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值