方式一:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();//打开文件对话框,筛选excel表格
fd.Filter = "表格|*.xls";//打开文件对话框筛选器
string strPath;
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
strPath = fd.FileName;
textBox3.Text = strPath;
DataSet ds = ExcelToDS(strPath);
DataTable dt = ds.Tables[0];
dataGridView1.DataSource= dt;
}
catch
{
Console.WriteLine();
}
}
}
public DataSet ExcelToDS(string Path)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds, "table1");
return ds;
}
方式二:文章来源地址https://www.toymoban.com/news/detail-743236.html
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();//打开文件对话框,筛选excel表格
fd.Filter = "表格|*.xls";//打开文件对话框筛选器
string strPath;
if(fd.ShowDialog() == DialogResult.OK)
{
try
{
strPath = fd.FileName;
//String strCon = "provider=microsoft.ACE.OLEDB.12.0;data source=" + strPath + ";extended properties=excel 8.0";
String strCon = "provider=microsoft.jet.oledb.4.0;data source=" + strPath + ";extended properties=excel 8.0";
OleDbConnection Con = new OleDbConnection(strCon);//建立连接
string strsql = "select *from [Sheet1$] ";
OleDbCommand cmd = new OleDbCommand(strsql, Con);//建立要执行的命令
OleDbDataAdapter da = new OleDbDataAdapter(cmd);//建立数据适配器
DataTable dt = new DataTable();
da.Fill(dt);// 把数据适配器中的数据读到DataTable中
dataGridView1.DataSource = dt;//指定数据源
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
文章来源:https://www.toymoban.com/news/detail-743236.html
到了这里,关于C# winform 将excel表格导入datagridView 的方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!