本文使用的是NPOI组件,可从网上下载。。数据库是mssqlserver, 其次,演示代码中是在解决方案中添加类库MyHelper,包含SqlHelperClass类!
首先是将数据表中的数据导出到Excel表:
1 ///2 /// 将数据表中的数据导出到Excel表格中 3 /// 4 private void btnOut_Click(object sender, EventArgs e) 5 { 6 string sql = "select * from dbo.T_Customers"; 7 using (SqlDataReader reader = SqlHelperClass.ExecuteReader(sql)) 8 { 9 if (reader.HasRows)10 {11 //首先创建一个workbook对象,Workbook实现IDisposible接口,需要using12 using (Workbook workbook = new HSSFWorkbook())13 {14 //创建一个sheet,15 using (Sheet sheet = workbook.CreateSheet("T_Customers"))16 {17 //创建表头行18 Row rowHeader = sheet.CreateRow(0);19 //循环为表头行的每一列添加标题20 for (int i = 0; i < reader.FieldCount; i++)21 {22 //将读取到的第一行数据(列名)作为Excel的列名23 rowHeader.CreateCell(i).SetCellValue(reader.GetName(i));24 }25 //接下来开始在sheet中加载内容26 int index = 1;27 while (reader.Read())28 {29 //根据查询的每一条数据都创建一行30 Row row = sheet.CreateRow(index);31 //遍历当前查询出的行32 for (int i = 0; i < reader.FieldCount; i++)33 {34 //首先要判断当前列中的数据是否为空35 if (reader.IsDBNull(i))36 {37 //如果为空,就给Excel单元格赋值空38 row.CreateCell(i).SetCellType(CellType.BLANK);39 }40 else41 {42 //如果不为空,则根据列的不同数据类型导出数据43 string dbType = reader.GetDataTypeName(i);44 switch (dbType)45 {46 case "int":47 row.CreateCell(i).SetCellValue(reader.GetInt32(i));48 break;49 case "datetime":50 row.CreateCell(i).SetCellValue(reader.GetDateTime(i).ToString("yyyy-MM-dd"));51 break;52 default :53 row.CreateCell(i).SetCellValue(reader.GetString(i));54 break;55 }56 }57 }58 index++;59 }60 //将workbook写入文件流,文件就房子Debug下吧。。可以修改61 using (FileStream fs = File.OpenWrite("Customers.xls"))62 {63 workbook.Write(fs);64 MessageBox.Show("ok");65 }66 }67 }68 }69 else70 {71 MessageBox.Show("表中没有数据!!!");72 }73 }74 }
接下来,演示将Excel数据导入到数据库表中:
1 ///2 /// 将Excel表格中的数据导入到数据表 3 /// 4 private void btnIn_Click(object sender, EventArgs e) 5 { 6 //读取Excel 7 using (FileStream fs = File.OpenRead("newCustomers.xls")) 8 { 9 //创建workbook10 using (Workbook workbook = new HSSFWorkbook(fs))11 {12 //获取第一个sheet13 using (Sheet sheet = workbook.GetSheetAt(0))14 {15 //sql 语句16 string sql = @"insert into T_Customers( CC_CustomerName, CC_CellPhone, CC_Landline,CC_CarNum,CC_BracketNum,CC_BuyDate) 17 values(@name,@phone,@lineNumber,@carNum,@Bid,@buydate)";18 19 //循环sheet中的每一行,注意是从第一行开始循环,因为第0行是标题,不需要读取20 for (int i = 1; i < sheet.LastRowNum; i++)21 {22 SqlParameter[] pms = new SqlParameter[] { 23 new SqlParameter("@name",SqlDbType.NVarChar),24 new SqlParameter("@phone",SqlDbType.VarChar),25 new SqlParameter("@lineNumber",SqlDbType.VarChar),26 new SqlParameter("@carNum",SqlDbType.VarChar),27 new SqlParameter("@Bid",SqlDbType.VarChar),28 new SqlParameter("@buydate",SqlDbType.DateTime)29 };30 Row row = sheet.GetRow(i);31 32 for (int j = 0; j < row.LastCellNum; j++)33 {34 //记住,三元表达式的冒号两边的数据类型一定是相容的35 pms[j].Value = row.GetCell(j) == null ? DBNull.Value : (object)row.GetCell(j).ToString();36 }37 SqlHelperClass.ExecuteNonQuery(sql, pms);38 }39 MessageBox.Show("ok");40 }41 }42 43 }44 }
另附我自己的sqlhelper类,配置文件中可根据自己的数据库写:
1 //连接字符串 2 private static readonly string conStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; 3 4 #region 执行增删改的NonQuery 5 public static int ExecuteNonQuery(string sql, params SqlParameter[] pms) 6 { 7 using (SqlConnection con = new SqlConnection(conStr)) 8 { 9 using (SqlCommand cmd = new SqlCommand(sql, con))10 {11 if (pms != null)12 {13 cmd.Parameters.AddRange(pms);14 }15 con.Open();16 return cmd.ExecuteNonQuery();17 }18 }19 }20 #endregion21 22 #region 执行返回多行多列方法Reader23 public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)24 {25 //由于DataReader使用时,要保证连接对象是打开的,所以这里SqlConnection不能using. 26 SqlConnection con = new SqlConnection(conStr);27 try28 {29 using (SqlCommand cmd = new SqlCommand(sql, con))30 {31 if (pms != null)32 {33 cmd.Parameters.AddRange(pms);34 }35 con.Open();36 return cmd.ExecuteReader(CommandBehavior.CloseConnection);37 }38 }39 catch40 {41 con.Close();42 con.Dispose();43 throw;44 }45 }46 #endregion