本篇文章主要介绍C# winForm窗体如何打开Excel文件读取其中的内容,并将其内容写到数据库,同时通过DataGridView控件显示写入到数据库的数据内容。
我的主窗体上添加了一个按钮和一个DataGridView控件,点击按钮来选择Excel文件,实例代码如下:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Files|*.xls;*.xlsx"; //设置打开文件的后缀类型
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);//打开我的电脑文件夹
string fileType = ".xls,.xlsx";
if (openFileDialog.ShowDialog()==DialogResult.OK)
{
string filePathAndName = openFileDialog.FileName;//文件路径以及文件名
string fileName = System.IO.Path.GetFileName(filePathAndName); //获取文件名和扩展名
string fileEx = System.IO.Path.GetExtension(fileName);//获取文件的扩展名
if (fileType.Contains(fileEx))
{
DataSet myDataSet = new DataSet();
try
{
//连接字符串 其中 "HDR=yes;"是说Excel文件的第一行是列名而不是数据,"HDR=No;"正好与前面的相反。
// 其中 "IMEX=1 "如果列中的数据类型不一致,使用"IMEX=1"可必免数据类型冲突。
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + filePathAndName + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; //此连接可以操作.xls与.xlsx文件
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
//返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//包含excel中表名的字符串数组
string[] strTableNames = new string[dtSheetName.Rows.Count];
for (int i = 0; i < dtSheetName.Rows.Count; i++)
{
strTableNames[i] = dtSheetName.Rows[i]["TABLE_NAME"].ToString();
}
OleDbDataAdapter myCommand = null;
DataTable dt = new DataTable();
//从指定的表名查询数据,这里选择第一个
string strExcel = "select * from [" + strTableNames[0] + "]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(myDataSet, "ExcelInfo");
DataTable table = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
//接下来将数据写入到数据库
//......
}
catch (Exception ex)
{
MessageBox.Show(""+ ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
throw;
}
}
else
MessageBox.Show("文件类型不对", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
因为我的Excel表里存放的是人员信息,所以我用一个user实体来接收然后写到数据库,示例代码如下:
dataGridView1.DataSource = null; //清空dataGridView
//dataGridView1.DataSource = table; //绑定数据源 我是一条条更新的数据 所以此处注释掉
User user = new User();
DBHelp db = new DBHelp();
for (int i = 0; i < table.Rows.Count; i++)
{
user.Name = table.Rows[i][1].ToString();
user.Job = table.Rows[i][2].ToString();
user.Email = table.Rows[i][3].ToString();
user.Phone1 = table.Rows[i][4].ToString();
user.Phone2 = table.Rows[i][5].ToString();
db.Insert(user); //数据写入数据库
UpdateUI(user);//dataGridView新增一行数据
}
MessageBox.Show("数据导入完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
每插入数据库一行数据便通过dataGridView控件更新显示一条数据,示例代码如下:
public void UpdateUI(User user)
{
//利用dataGridView1.Rows.Add()事件为DataGridView控件增加新的行,
//该函数返回添加新行的索引号,即新行的行号
int index = this.dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index + 1;
dataGridView1.Rows[index].Cells[1].Value = user.Name;
dataGridView1.Rows[index].Cells[2].Value = user.Job;
dataGridView1.Rows[index].Cells[3].Value = user.Email;
dataGridView1.Rows[index].Cells[4].Value = user.Phone1;
dataGridView1.Rows[index].Cells[5].Value = user.Phone2;
}
不过,运行该程序便会发现问题,UpdateUI方法并不能做到插入一条数据便更新显示一条数据,每次都是全部数据插入完后才会显示全部的数据内容,显然,这不是我们想要的效果,不过,在UpdateUI方法中加入以下任意一个方法就可以解决这个问题了,如下:
dataGridView1.Refresh();//重绘控件
dataGridView1.Update();//重绘控件
另外需要注意的是,dataGridView控件需要在加载的时候设置一下列的属性,比如我这样:
dataGridView1.ColumnCount = 6; //列数
dataGridView1.ColumnHeadersVisible = true; //显示列标题
dataGridView1.Columns[0].Name = "编号";
dataGridView1.Columns[1].Name = "姓名";
dataGridView1.Columns[2].Name = "部门";
dataGridView1.Columns[3].Name = "邮箱";
dataGridView1.Columns[4].Name = "电话";
dataGridView1.Columns[5].Name = "手机";
ok
到此结束。