zoukankan      html  css  js  c++  java
  • excel数据导入数据库

     1 using (FileStream fs = File.OpenRead(@"D:成绩管理名单.xls"))
     2             {
     3                 IWorkbook wk = new HSSFWorkbook(fs);//根据文件流创建workbook
     4                 if (wk.NumberOfSheets > 0)
     5                 {
     6                     ISheet sheet = wk.GetSheetAt(0);//创建工作表
     7                     //学号    姓名    性别    出生年月  专业
     8                     for (int r = 1; r <= sheet.LastRowNum; r++)//r=1,从第1行开始读取,而不是第0行,第0行是列名
    9 { 10 #region 获取excel数据 11 IRow row = sheet.GetRow(r); 12 int stuid; 13 if (row.GetCell(0).CellType==CellType.BLANK)//主键stuid不允许空,若为空则跳过该行数据 14 { 15 continue; 16 } 17 else 18 { 19 stuid = (int)row.GetCell(0).NumericCellValue; 20 } 21 string name = row.GetCell(1) == null ? null : row.GetCell(1).StringCellValue; 22 string gender = row.GetCell(2)==null ? null: row.GetCell(2).StringCellValue; 23 string birth = row.GetCell(3) == null? null : row.GetCell(3).StringCellValue; 24 string specialty = row.GetCell(4)==null ? null : row.GetCell(4).StringCellValue; 25 #endregion 26 27 string sql = "insert into ceshi values(@stuid,@name,@birth,@gender,@specialty)"; 28 SqlParameter[] para = new SqlParameter[]{ 29 new SqlParameter("@stuid",stuid), 30 //空值在C#中是null,但通过sql语句向数据库中插入null值应为DBNull.Value 31 new SqlParameter("@name",name==null?DBNull.Value:(object)name), 32 new SqlParameter("@birth",birth==null?DBNull.Value:(object)birth), 33 new SqlParameter("@gender",gender==null?DBNull.Value:(object)gender), 34 new SqlParameter("@specialty",specialty==null?DBNull.Value:(object)specialty), 35 }; 36 using (cmd = new SqlCommand(sql, GetConn())) 37 { 38 if (para!=null) 39 { 40 cmd.Parameters.AddRange(para); 41 } 42 cmd.ExecuteNonQuery(); 43 } 44 } 45 MessageBox.Show("导入成功"); 46 } 47 }
  • 相关阅读:
    BZOJ3124 直径
    BZOJ1491 洛谷2047 NOI2007 社交网络
    TYVJ1423 GF和猫咪的玩具
    poj 3463 Sightseeing
    TYVJ2032 升降梯上
    NOIP2009 codevs1173 洛谷P1073 最优贸易
    [BZOJ1066] [SCOI2007] 蜥蜴 (网络流)
    [BZOJ3293] [Cqoi2011] 分金币 (贪心)
    [BZOJ1045] [HAOI2008] 糖果传递 (贪心)
    [BZOJ1005] [HNOI2008] 明明的烦恼 (prufer编码)
  • 原文地址:https://www.cnblogs.com/lpynb/p/3940555.html
Copyright © 2011-2022 走看看