C# 您所在的位置:网站首页 word导入excel数据库 C#

C#

2023-11-12 14:48| 来源: 网络整理| 查看: 265

以下是学习笔记:

一,实现效果:

1,原始的Excel数据:

 

 2,点击“从外部Excel文件导入数据”。把上面的Excel文件导入UI显示

 

 3,点击“保存到数据库” 又可以把UI的数据保存在SqlServer数据库

 

 

4,分析实现以上功能的思路

 

 一,编写一个能够读取Excel的通用数据访问类OleDbHelper

 

OleDbHelper代码:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.OleDb; namespace DAL.Helper { class OleDbHelper { //适合Excel2003版本 // private static string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0"; //适合Excel2007以后的版本 private static string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0"; /// /// 执行增、删、改(insert/update/delete) /// /// /// public static int Update(string sql) { OleDbConnection conn = new OleDbConnection(connString); OleDbCommand cmd = new OleDbCommand(sql, conn); try { conn.Open(); int result = cmd.ExecuteNonQuery(); return result; } catch (Exception ex) { //写入日志。。。 throw ex; } finally { conn.Close(); } } /// /// 执行单一结果查询(select) /// /// /// public static object GetSingleResult(string sql) { OleDbConnection conn = new OleDbConnection(connString); OleDbCommand cmd = new OleDbCommand(sql, conn); try { conn.Open(); object result = cmd.ExecuteScalar(); return result; } catch (Exception ex) { //写入日志。。。 throw ex; } finally { conn.Close(); } } /// /// 执行多结果查询(select) /// /// /// public static OleDbDataReader GetReader(string sql) { OleDbConnection conn = new OleDbConnection(connString); OleDbCommand cmd = new OleDbCommand(sql, conn); try { conn.Open(); OleDbDataReader objReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return objReader; } catch (Exception ex) { conn.Close(); throw ex; } } /// /// 执行返回数据集的查询 /// /// /// public static DataSet GetDataSet(string sql) { OleDbConnection conn = new OleDbConnection(connString); OleDbCommand cmd = new OleDbCommand(sql, conn); OleDbDataAdapter da = new OleDbDataAdapter(cmd); //创建数据适配器对象 DataSet ds = new DataSet();//创建一个内存数据集 try { conn.Open(); da.Fill(ds); //使用数据适配器填充数据集 return ds; //返回数据集 } catch (Exception ex) { //写入日志。。。 throw ex; } finally { conn.Close(); } } /// /// 读取数据到DataSet中 /// /// /// /// public static DataSet GetDataSet(string sql, string path) { OleDbConnection conn = new OleDbConnection(string.Format(connString, path)); OleDbCommand cmd = new OleDbCommand(sql, conn); OleDbDataAdapter da = new OleDbDataAdapter(cmd); //创建数据适配器对象 DataSet ds = new DataSet();//创建一个内存数据集 try { conn.Open(); da.Fill(ds); //使用数据适配器填充数据集 return ds; //返回数据集 } catch (Exception ex) { //写入日志。。。 throw ex; } finally { conn.Close(); } } } }

  

二,编写ImportDataFromExcel类,添加查询Excel数据表的方法。

操作Excel跟操作SqlServer很类似,

注意:ImportDataFromExcel类很难做到通用,这个根据客户的表结构和实体属型来定制的

工作薄:整个Execl文件,类似数据库

工作表:类似的数据库的一张表

 

 

ImportDataFromExcel类代码:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.OleDb; using Models; namespace DAL.Helper { /// /// 从Excel中导入数据 /// public class ImportDataFromExcel { /// /// 从Excel文件中读取数据 /// /// Excel文件的路径 /// 对象的集合 public List GetStudentByExcel(string path) { List list = new List(); DataSet ds = OleDbHelper.GetDataSet("select * from [Student$] ", path); DataTable dt = ds.Tables[0]; foreach (DataRow row in dt.Rows) { list.Add(new Student() { StudentName = row["姓名"].ToString(), Gender = row["性别"].ToString(), Birthday = Convert.ToDateTime(row["出生日期"]), Age = DateTime.Now.Year - Convert.ToDateTime(row["出生日期"]).Year, CardNo = row["考勤卡号"].ToString(), StudentIdNo = row["身份证号"].ToString(), PhoneNumber = row["电话号码"].ToString(), StudentAddress = row["家庭住址"].ToString(), ClassId = Convert.ToInt32(row["班级编号"]) }); } return list; } /// /// 将集合中的对象插入到SqlServer数据库 /// /// /// public bool Import(List list) { List sqlList = new List(); StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.Append("insert into Students(studentName,Gender,Birthday,"); sqlBuilder.Append("StudentIdNo,Age,PhoneNumber,StudentAddress,CardNo,ClassId)"); sqlBuilder.Append(" values('{0}','{1}','{2}',{3},{4},'{5}','{6}','{7}',{8})"); foreach (Student objStudent in list) { string sql = string.Format(sqlBuilder.ToString(), objStudent.StudentName, objStudent.Gender, objStudent.Birthday, objStudent.StudentIdNo, objStudent.Age, objStudent.PhoneNumber, objStudent.StudentAddress, objStudent.CardNo, objStudent.ClassId); sqlList.Add(sql); } return SQLHelper.UpdateByTran(sqlList); } } }

  

三,在DataGridView中展示Excel中导入的数据

 

 

4,在SQLHelper类中编写同事“插入多条SQL语句的事务UpdateByTran方法 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace DAL { /// /// 通用数据访问类 /// class SQLHelper { // private static readonly string connString = "Server=.;DataBase=StudentManageDB;Uid=sa;Pwd=password01!"; private static readonly string connString = ConfigurationManager.ConnectionStrings["connString"].ToString(); //private static readonly string connString = // Common.StringSecurity.DESDecrypt(ConfigurationManager.ConnectionStrings["connString"].ToString()); /// /// 执行增、删、改(insert/update/delete) /// /// /// public static int Update(string sql) { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql, conn); try { conn.Open(); int result = cmd.ExecuteNonQuery(); return result; } catch (Exception ex) { throw ex; } finally { conn.Close(); } } /// /// 执行单一结果查询(select) /// /// /// public static object GetSingleResult(string sql) { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql, conn); try { conn.Open(); object result = cmd.ExecuteScalar(); return result; } catch (Exception ex) { throw ex; } finally { conn.Close(); } } /// /// 执行多结果查询(select) /// /// /// public static SqlDataReader GetReader(string sql) { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql, conn); try { conn.Open(); SqlDataReader objReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return objReader; } catch (Exception ex) { conn.Close(); throw ex; } } /// /// 执行返回数据集的查询 /// /// /// public static DataSet GetDataSet(string sql) { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataAdapter da = new SqlDataAdapter(cmd); //创建数据适配器对象 DataSet ds = new DataSet();//创建一个内存数据集 try { conn.Open(); da.Fill(ds); //使用数据适配器填充数据集 return ds; //返回数据集 } catch (Exception ex) { throw ex; } finally { conn.Close(); } } /// /// 启用事务执行多条SQL语句 /// /// SQL语句列表 /// public static bool UpdateByTran(List sqlList) { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; try { conn.Open(); cmd.Transaction = conn.BeginTransaction(); //开启事务 foreach (string itemSql in sqlList)//循环提交SQL语句 { cmd.CommandText = itemSql; cmd.ExecuteNonQuery(); } cmd.Transaction.Commit(); //提交事务(同时自动清除事务) return true; } catch (Exception ex) { if (cmd.Transaction != null) cmd.Transaction.Rollback();//回滚事务(同时自动清除事务) throw new Exception("调用事务方法UpdateByTran(List sqlList)时出现错误:" + ex.Message); } finally { if (cmd.Transaction != null) cmd.Transaction = null; conn.Close(); } } /// /// 获取服务器的时间 /// /// public static DateTime GetServerTime() { return Convert.ToDateTime(GetSingleResult("select getdate()")); } } }

  

5,在ImportDataFromExcel类中,编写保存“多个集合对象的”的方法

 

 

6,在UI中将导入的数据保存在SQL数据库 //保存到数据库 private void btnSaveToDB_Click(object sender, EventArgs e) { //【1】验证数据(保证List集合中有数据) if (list == null || list.Count == 0) { MessageBox.Show("目前没有要导入的数据!", "导入提示"); return; } //【2】遍历集合(方法1:每查询一个对象,就提交一次数据) //(方法2:每遍历一次,就生成一条SQL语句) try { if (new DAL.Helper.ImportDataFromExcel().Import(this.list)) { MessageBox.Show("数据导入成功!", "导入提示"); this.dgvStudentList.DataSource = null; this.list.Clear(); } else { MessageBox.Show("数据导入失败!", "导入提示"); } } catch (Exception ex) { MessageBox.Show("数据导入失败!具体原因:" + ex.Message, "导入提示"); } }

  



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有