private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = null; //每次打开清空内容
DataSet dataSet = getData();//调用关联方法1-1;
if (dataSet != null)
{
DataTable dt = dataSet.Tables[0];
RemoveEmpty(dt);
dataGridView1.DataSource = dt;
}
}
/// <summary>
/// 获取数据方法;
/// </summary>
/// <returns></returns>
/// 01
public DataSet getData()
{
//打开文件
OpenFileDialog file = new OpenFileDialog();
//file.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
file.Filter = "Excel文件 |*.xlsx;*.xls";
file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
file.Multiselect = false;
if (file.ShowDialog() == DialogResult.Cancel)
return null;
//判断文件后缀
var path = file.FileName;
textBox1.Text = path;
string fileSuffix = System.IO.Path.GetExtension(path);
if (string.IsNullOrEmpty(fileSuffix))
return null;
using (DataSet ds = new DataSet())
{
//判断Excel文件是2003版本还是2007版本
string connString = "";
if (fileSuffix == ".xls")
connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
//string Sql = "";
//读取文件 bug-01,限定Excel名字的地方。可以修改测试;
string sql_select = " SELECT * FROM [Sheet1$]";
//need-1 自定义Excel工作表名字; 程序写死工作表名字方式,上面的是通用方式。程序写死成功,读取指定的工作表,可以读取指定的工作表。
using (OleDbConnection conn = new OleDbConnection(connString))
using (OleDbDataAdapter cmd = new OleDbDataAdapter(sql_select, conn))
{
conn.Open();
cmd.Fill(ds);
}
if (ds == null || ds.Tables.Count <= 0) { return null; }
return ds;
}
}
/// <summary>
/// 去除表格中的空行;
/// </summary>
/// <param name="dt"></param>
//这个函数主要是用于去除表格中的空行 02
protected void RemoveEmpty(DataTable dt)
{
List<DataRow> removelist = new List<DataRow>();
for (int i = 0; i < dt.Rows.Count; i++)
{
bool IsNull = true;
for (int j = 0; j < dt.Columns.Count; j++)
{
if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
{
IsNull = false;
}
}
if (IsNull)
{
removelist.Add(dt.Rows[i]);
}
}
for (int i = 0; i < removelist.Count; i++)
{
dt.Rows.Remove(removelist[i]);
}
}
效果
文章来源:https://www.toymoban.com/news/detail-744873.html
文章来源地址https://www.toymoban.com/news/detail-744873.html
到了这里,关于winform读取Excel文件中数据内容的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!