项目中要用到excel导入数据,用NPOI方式做了一个demo,记录如下:
Form1代码:
1 public Form1() 2 { 3 InitializeComponent(); 4 } 5 6 private void button1_Click(object sender, EventArgs e) 7 { 8 OpenFileDialog f = new OpenFileDialog(); 9 f.Multiselect = true; 10 f.ShowDialog(); 11 string[] filenames = f.FileNames; 12 13 if (filenames.Length > 0) 14 { 15 this.label1.Text = filenames[0]; 16 string strFile = System.IO.Path.GetFileName(filenames[0]); 17 DataTable dt = GetDataBySQLNew("McsDW", "select 1 from [McsDW].[dbo].[UserGateWayNumber] where ExcelFileName='" + strFile + "'"); 18 if (dt != null) 19 { 20 if (dt.Rows.Count > 0) 21 { 22 MessageBox.Show("数据库里已经导入名称为 " + strFile + " 的excel表,请核对!"); 23 this.label1.Text = ""; 24 } 25 } 26 } 27 } 28 29 private void button2_Click(object sender, EventArgs e) 30 { 31 if (this.label1.Text.Length < 1) 32 { 33 MessageBox.Show("请先选择excel文件!"); 34 return; 35 } 36 string sheetIndex = texBoxSheet.Text; 37 int sheetInt = 1; 38 int.TryParse(sheetIndex, out sheetInt); 39 if (sheetInt < 1) 40 { 41 MessageBox.Show("sheet序号请填写整数!"); 42 return; 43 } 44 45 ReadFromExcelFile(this.label1.Text, sheetInt); 46 } 47 48 private DataSet ExcelToDS(string Path) 49 { 50 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;"; 51 OleDbConnection conn = new OleDbConnection(strConn); 52 conn.Open(); 53 string strExcel = ""; 54 OleDbDataAdapter myCommand = null; 55 DataSet ds = null; 56 strExcel = "select * from [sheet1$]"; 57 myCommand = new OleDbDataAdapter(strExcel, strConn); 58 ds = new DataSet(); 59 myCommand.Fill(ds, "table1"); 60 return ds; 61 } 62 63 private void TestExcelRead(string file) 64 { 65 try 66 { 67 using (ExcelHelper excelHelper = new ExcelHelper(file)) 68 { 69 DataTable dt = excelHelper.ExcelToDataTable("MySheet", true); 70 int SE = dt.Rows.Count; 71 //PrintData(dt); 72 } 73 } 74 catch (Exception ex) 75 { 76 Console.WriteLine("Exception: " + ex.Message); 77 } 78 } 79 80 81 private void ReadFromExcelFile(string filePath, int sheetInt) 82 { 83 IWorkbook wk = null; 84 string extension = System.IO.Path.GetExtension(filePath); 85 try 86 { 87 FileStream fs = File.OpenRead(filePath); 88 if (extension.Equals(".xls"))//xlsx xls 89 { 90 //把xls文件中的数据写入wk中 91 wk = new HSSFWorkbook(fs); 92 } 93 else 94 { 95 //把xlsx文件中的数据写入wk中 96 wk = new XSSFWorkbook(fs); 97 } 98 99 fs.Close(); 100 //读取当前表数据 101 string userCount = ""; 102 Dictionary<string, List<string>> userDic = new Dictionary<string, List<string>>(); 103 if (sheetInt > wk.NumberOfSheets) 104 { 105 MessageBox.Show("sheet序号填写超出范围!"); 106 return; 107 } 108 //for (int k = 0; k < wk.NumberOfSheets; k++ ) 109 //{ 110 111 ISheet sheet = wk.GetSheetAt(sheetInt-1); 112 113 IRow row = sheet.GetRow(0); //读取当前行数据 114 //LastRowNum 是当前表的总行数-1(注意) 115 int offset = 0; 116 117 for (int i = 0; i <= sheet.LastRowNum; i++) 118 { 119 row = sheet.GetRow(i); //读取当前行数据 120 if (row != null) 121 { 122 string uxuhao = "", udanwei = "", ubumen = "", ubianhao = "", uname = "", uAka = "", uBka = "", ukai = ""; 123 //LastCellNum 是当前行的总列数 124 for (int j = 0; j < row.LastCellNum; j++) 125 { 126 //读取该行的第j列数据 127 string value = row.GetCell(j) == null ? "" : row.GetCell(j).ToString(); 128 129 if (j == 0) 130 uxuhao = value; 131 else if (j == 1) 132 udanwei = value; 133 else if (j == 2) 134 ubumen = value; 135 else if (j == 3) 136 ubianhao = value; 137 else if (j == 4) 138 uname = value; 139 else if (j == 5) 140 uAka = value; 141 else if (j == 6) 142 uBka = value; 143 else if (j == 7) 144 { 145 ukai = value; 146 if(uxuhao != null) 147 { 148 if (uxuhao.Contains("计数")) 149 { 150 ukai = row.GetCell(j).NumericCellValue.ToString(); 151 } 152 } 153 154 } 155 156 } 157 if (!(ubianhao.Equals("") || ubianhao.Equals("员工编号") || ubianhao.Contains("经办人"))) 158 { 159 List<string> ulist = new List<string>(); 160 ulist.Add(udanwei); 161 ulist.Add(ubumen); 162 ulist.Add(uname); 163 ulist.Add(ukai); 164 ulist.Add(uAka); 165 ulist.Add(uBka); 166 userDic.Add(ubianhao, ulist); 167 //Console.WriteLine(" "); 168 } 169 if (uxuhao != null) 170 { 171 if (uxuhao.Contains("计数")) 172 { 173 userCount = ukai; 174 break; 175 } 176 int uxuhaoInt = 0; 177 int.TryParse(uxuhao, out uxuhaoInt); 178 if (userDic.Count > 0 && uxuhaoInt == 0) 179 { 180 userCount = "没有计数"; 181 break; 182 } 183 } 184 } 185 } 186 //} 187 188 DoUser(userDic, filePath, userCount, sheetInt); 189 } 190 191 catch (Exception e) 192 { 193 //只在Debug模式下才输出 194 Console.WriteLine(e.Message); 195 MessageBox.Show(e.Message); 196 } 197 } 198 199 private void DoUser(Dictionary<string, List<string>> userDic, string filePath, string userCount, int sheetInt) 200 { 201 if (userDic.Count < 1) 202 return; 203 string namev = ""; 204 string tip = ""; 205 DataTable dtNew = new DataTable(); 206 try 207 { 208 // 209 DataTable dt = GetDataBySQLNew("McsDW", "select * from UserViewAll_DW "); 210 211 dtNew.Columns.Add("员工编号", Type.GetType("System.String")); 212 dtNew.Columns.Add("姓名", Type.GetType("System.String")); 213 dtNew.Columns.Add("A卡", Type.GetType("System.String")); 214 dtNew.Columns.Add("B卡", Type.GetType("System.String")); 215 dtNew.Columns.Add("开通餐卡", Type.GetType("System.String")); 216 dtNew.Columns.Add("备注", Type.GetType("System.String")); 217 218 string sql = "", sqlabnull = ""; 219 string remark = ""; 220 int passCount = 0; 221 DataTable dtNewABNull = dtNew.Clone(); 222 223 foreach (var d in userDic) 224 { 225 //Console.Write(d.Key+"----"+d.Value); 226 //Console.WriteLine(" "); 227 //namev = d.Value; 228 remark = ""; 229 bool isExcel = false; 230 DataRow[] rows = dt.Select("PostionLevel='" + d.Key + "'"); 231 //if (d.Value[3].Trim().Equals("否")) 232 // continue; 233 //开通餐卡为空,默认为不开通 234 if (d.Value[3].Trim().Equals("")) 235 { 236 //Console.WriteLine(d.Key + "----" + d.Value + "----开通餐卡为空"); 237 //isExcel = true; 238 //remark = "开通餐卡为空!"; 239 continue; 240 } 241 //开通餐卡,填的不是A,B 242 if (!(d.Value[3].Trim().ToUpper().Equals("A") || d.Value[3].Trim().ToUpper().Equals("B"))) 243 { 244 isExcel = true; 245 remark += "开通餐卡项填写错误,填的不是A,B"; 246 } 247 //如果开通A卡但是A卡为空,B卡不为空,也提示 248 else if (d.Value[3].Trim().ToUpper().Equals("A") && d.Value[4].Trim().Equals("") && !d.Value[5].Trim().Equals("")) 249 { 250 isExcel = true; 251 remark += "需要开通A卡但是A卡为空,B卡不为空,请填B卡"; 252 } 253 //如果开通B卡但是B卡为空,A卡不为空,也提示 254 else if (d.Value[3].Trim().ToUpper().Equals("B") && d.Value[5].Trim().Equals("") && !d.Value[4].Trim().Equals("")) 255 { 256 isExcel = true; 257 remark += "需要开通B卡但是B卡为空,A卡不为空,请填A卡"; 258 } 259 else if (rows == null) 260 { 261 isExcel = true; 262 remark += "数据库为空"; 263 } 264 else if (rows.Length < 1) 265 { 266 isExcel = true; 267 remark += "数据库找不到该用户"; 268 } 269 else 270 { 271 //判断用户名,中文名字 272 if (!(d.Value[2].Trim().Equals(rows[0]["UserDisplayName"].ToString().Trim()))) 273 { 274 isExcel = true; 275 remark += "数据库里该用户名不匹配:" + rows[0]["UserDisplayName"].ToString(); 276 } 277 //如果开通A卡,判断A卡和数据库是否匹配 278 if (d.Value[3].Trim().ToUpper().Equals("A") && !(d.Value[4].Trim().Equals(rows[0]["GatewayNumber"].ToString().Trim()))) 279 { 280 isExcel = true; 281 remark += "开通A卡,但数据库里该用户A卡不匹配:" + rows[0]["GatewayNumber"].ToString(); 282 } 283 //如果开通B卡,判断B卡和数据库是否匹配 284 if (d.Value[3].Trim().ToUpper().Equals("B") && !(d.Value[5].Trim().Equals(rows[0]["GatewayNumber2"].ToString().Trim()))) 285 { 286 isExcel = true; 287 remark += "开通B卡,但数据库里该用户B卡不匹配:" + rows[0]["GatewayNumber2"].ToString(); 288 } 289 //string kastr = GetKa(rows[0]["GatewayNumber2"], rows[0]["GatewayNumber"]); 290 //if (kastr.Equals("") || kastr.Equals("没有卡号")) 291 //{ 292 // isExcel = true; 293 // remark += "数据库里该用户卡号有误:" + kastr; 294 //} 295 } 296 297 string Gender = GetGender(d.Key); 298 //如果A卡和B卡都为空,也提示 299 if (d.Value[4].Trim().Equals("") && d.Value[5].Trim().Equals("")) 300 { 301 string abnull = "A,B卡都为空,请尽快启动办卡流程"; 302 dtNewABNull.Rows.Add(new object[] { d.Key, d.Value[2], d.Value[4], d.Value[5], d.Value[3], abnull }); 303 304 sqlabnull += string.Format(" insert into UserGateWayNumberABNull(UnitName,DepartmentName,PostionLevel,UserName,GatewayNumber,ExcelFileName,AorBcard,Remark,Gender) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", 305 d.Value[0], d.Value[1], d.Key, d.Value[2], "", System.IO.Path.GetFileName(filePath), d.Value[3], abnull, Gender); 306 passCount++; 307 continue; 308 } 309 310 if (isExcel) 311 { 312 DataRow r = dtNew.NewRow(); 313 r["员工编号"] = d.Key; 314 r["姓名"] = d.Value[2]; 315 r["A卡"] = d.Value[4]; 316 r["B卡"] = d.Value[5]; 317 r["开通餐卡"] = d.Value[3]; 318 r["备注"] = remark; 319 320 dtNew.Rows.Add(r); 321 } 322 else 323 { 324 string gNum = ""; 325 if (d.Value[3].Trim().ToUpper().Equals("A")) 326 gNum = d.Value[4]; 327 else 328 gNum = d.Value[5]; 329 330 sql += string.Format(" insert into UserGateWayNumber(UnitName,DepartmentName,PostionLevel,UserName,GatewayNumber,ExcelFileName,AorBcard,Gender) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", 331 d.Value[0], d.Value[1], d.Key, d.Value[2], gNum, System.IO.Path.GetFileName(filePath), d.Value[3], Gender); 332 passCount++; 333 } 334 } 335 //WriteToExcel(@"F:/web/设计院档案文档/用印不归档/员工卡号.xls"); 336 int ucount =0; 337 int.TryParse(userCount, out ucount); 338 if (dtNew.Rows.Count > 0) 339 { 340 //DataRow r = dtNew.NewRow(); 341 //r["员工编号"] = filePath; 342 //r["姓名"] = ""; 343 //r["A卡"] = ""; 344 //r["B卡"] = ""; 345 //r["开通餐卡"] = ""; 346 //r["备注"] = ""; 347 348 //dtNew.Rows.Add(r); 349 //加入AB都为空的用户 350 foreach(DataRow ro in dtNewABNull.Rows) 351 { 352 dtNew.Rows.Add(ro.ItemArray); 353 } 354 //加入excel名 355 dtNew.Rows.Add(new object[] { filePath, "", "", "", "", "" }); 356 357 DataTableToExcel(dtNew); 358 tip = "总共处理了" + userDic.Count + "条数据,其中异常的有" + (dtNew.Rows.Count-1).ToString() + "条。请查看D:/食堂餐卡统计.xls"; 359 } 360 else if (ucount != passCount && !userCount.Equals("没有计数")) 361 { 362 tip = "总共处理了" + userDic.Count + "条数据,其中合格数据有" + passCount + "条, excel表中计数的有" + ucount + "条。数据不匹配,请核查!"; 363 } 364 else 365 { 366 //GetDataBySQLNew("McsDW", sql + sqlabnull); 367 //tip = "总共处理了" + userDic.Count + "条数据,其中合格数据有" + (passCount - dtNewABNull.Rows.Count).ToString() + "条,数据已经录入到[McsDW].[dbo].[UserGateWayNumber]表中, AB卡都为空但是需要开通卡的用户数据有" + dtNewABNull.Rows.Count + "条,此数据录入到表UserGateWayNumberABNull"; 368 } 369 } 370 catch(Exception e) 371 { 372 MessageBox.Show(e.Message + "--" + namev); 373 } 374 375 Console.Write("总共"+userDic.Count); 376 MessageBox.Show(tip); 377 } 378 379 private string GetGender(string pl) 380 { 381 string sql = "select Gender from [McsDW].[dbo].[UserViewAll_DW] where PostionLevel='" + pl + "'"; 382 DataTable dt = GetDataBySQLNew("McsDW", sql); 383 if (dt == null || dt.Rows.Count < 1) 384 return ""; 385 return dt.Rows[0][0] == null ? "" : dt.Rows[0][0].ToString(); 386 } 387 388 private string GetKa(object K2, object K1) 389 { 390 if (!(K2 == null || K2.Equals(""))) 391 { 392 return K2.ToString(); 393 } 394 else if (!(K1 == null || K1.Equals(""))) 395 { 396 return K1.ToString(); 397 } 398 else 399 return "没有卡号"; 400 } 401 402 private void WriteToExcel(string filePath) 403 { 404 //创建工作薄 405 IWorkbook wb; 406 string extension = System.IO.Path.GetExtension(filePath); 407 //根据指定的文件格式创建对应的类 408 if (extension.Equals(".xls")) 409 { 410 wb = new HSSFWorkbook(); 411 } 412 else 413 { 414 wb = new XSSFWorkbook(); 415 } 416 417 ICellStyle style1 = wb.CreateCellStyle();//样式 418 style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式 419 style1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式 420 //设置边框 421 style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; 422 style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; 423 style1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; 424 style1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; 425 style1.WrapText = true;//自动换行 426 427 ICellStyle style2 = wb.CreateCellStyle();//样式 428 IFont font1 = wb.CreateFont();//字体 429 font1.FontName = "楷体"; 430 font1.Color = HSSFColor.Red.Index;//字体颜色 431 font1.Boldweight = (short)FontBoldWeight.Normal;//字体加粗样式 432 style2.SetFont(font1);//样式里的字体设置具体的字体样式 433 //设置背景色 434 style2.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index; 435 style2.FillPattern = FillPattern.SolidForeground; 436 style2.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index; 437 style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式 438 style2.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式 439 440 ICellStyle dateStyle = wb.CreateCellStyle();//样式 441 dateStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式 442 dateStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式 443 //设置数据显示格式 444 IDataFormat dataFormatCustom = wb.CreateDataFormat(); 445 dateStyle.DataFormat = dataFormatCustom.GetFormat("yyyy-MM-dd HH:mm:ss"); 446 447 //创建一个表单 448 ISheet sheet = wb.CreateSheet("Sheet0"); 449 //设置列宽 450 int[] columnWidth = { 10, 10, 20, 10 }; 451 for (int i = 0; i < columnWidth.Length; i++) 452 { 453 //设置列宽度,256*字符数,因为单位是1/256个字符 454 sheet.SetColumnWidth(i, 256 * columnWidth[i]); 455 } 456 457 //测试数据 458 int rowCount = 2, columnCount = 4; 459 // object[,] data = { 460 // {"列0", "列1", "列2", "列3"}, 461 // {"", 400, 5.2, 6.01}, 462 // {"", true, "2014-07-02", DateTime.Now} 463 // //日期可以直接传字符串,NPOI会自动识别 464 // //如果是DateTime类型,则要设置CellStyle.DataFormat,否则会显示为数字 465 //}; 466 object[,] data = { 467 {"列0", "列1", "列2", "列3"}, 468 {"", 400, 5.2, 6.01} 469 }; 470 471 IRow row; 472 ICell cell; 473 474 for (int i = 0; i < rowCount; i++) 475 { 476 row = sheet.CreateRow(i);//创建第i行 477 for (int j = 0; j < columnCount; j++) 478 { 479 cell = row.CreateCell(j);//创建第j列 480 cell.CellStyle = j % 2 == 0 ? style1 : style2; 481 //根据数据类型设置不同类型的cell 482 object obj = data[i, j]; 483 SetCellValue(cell, data[i, j]); 484 //如果是日期,则设置日期显示的格式 485 if (obj.GetType() == typeof(DateTime)) 486 { 487 cell.CellStyle = dateStyle; 488 } 489 //如果要根据内容自动调整列宽,需要先setCellValue再调用 490 //sheet.AutoSizeColumn(j); 491 } 492 } 493 494 //合并单元格,如果要合并的单元格中都有数据,只会保留左上角的 495 //CellRangeAddress(0, 2, 0, 0),合并0-2行,0-0列的单元格 496 CellRangeAddress region = new CellRangeAddress(0, 2, 0, 0); 497 sheet.AddMergedRegion(region); 498 499 try 500 { 501 FileStream fs = File.OpenWrite(filePath); 502 wb.Write(fs);//向打开的这个Excel文件中写入表单并保存。 503 fs.Close(); 504 } 505 catch (Exception e) 506 { 507 Console.WriteLine(e.Message); 508 } 509 } 510 private void SetCellValue(ICell cell, object obj) 511 { 512 if (obj.GetType() == typeof(int)) 513 { 514 cell.SetCellValue((int)obj); 515 } 516 else if (obj.GetType() == typeof(double)) 517 { 518 cell.SetCellValue((double)obj); 519 } 520 else if (obj.GetType() == typeof(IRichTextString)) 521 { 522 cell.SetCellValue((IRichTextString)obj); 523 } 524 else if (obj.GetType() == typeof(string)) 525 { 526 cell.SetCellValue(obj.ToString()); 527 } 528 else if (obj.GetType() == typeof(DateTime)) 529 { 530 cell.SetCellValue((DateTime)obj); 531 } 532 else if (obj.GetType() == typeof(bool)) 533 { 534 cell.SetCellValue((bool)obj); 535 } 536 else 537 { 538 cell.SetCellValue(obj.ToString()); 539 } 540 } 541 542 private bool DataTableToExcel(DataTable dt) 543 { 544 bool result = false; 545 IWorkbook workbook = null; 546 FileStream fs = null; 547 IRow row = null; 548 ISheet sheet = null; 549 ICell cell = null; 550 try 551 { 552 if (dt != null && dt.Rows.Count > 0) 553 { 554 workbook = new HSSFWorkbook(); 555 sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表 556 int rowCount = dt.Rows.Count;//行数 557 int columnCount = dt.Columns.Count;//列数 558 559 //设置列头 560 row = sheet.CreateRow(0);//excel第一行设为列头 561 for (int c = 0; c < columnCount; c++) 562 { 563 cell = row.CreateCell(c); 564 cell.SetCellValue(dt.Columns[c].ColumnName); 565 } 566 567 //设置每行每列的单元格, 568 for (int i = 0; i < rowCount; i++) 569 { 570 row = sheet.CreateRow(i + 1); 571 for (int j = 0; j < columnCount; j++) 572 { 573 cell = row.CreateCell(j);//excel第二行开始写入数据 574 cell.SetCellValue(dt.Rows[i][j].ToString()); 575 } 576 } 577 using (fs = File.OpenWrite(@"D:/食堂餐卡统计.xls")) 578 { 579 workbook.Write(fs);//向打开的这个xls文件中写入数据 580 result = true; 581 } 582 } 583 return result; 584 } 585 catch (Exception ex) 586 { 587 if (fs != null) 588 { 589 fs.Close(); 590 } 591 return false; 592 } 593 } 594 595 private DataTable GetDataBySQLNew(string database, string sql) 596 { 597 DataTable dt = new DataTable(); 598 string strServer = "Server=127.0.0.0; DataBase=McsDW; user id=sqluser; password=Pass@word123;"; 599 if (database.Equals("McsDW")) 600 { 601 strServer = "Server=127.0.0.0; DataBase=McsDW; user id=sqluser; password=Pass@word123;"; 602 } 603 else if (database.Equals("McsSP")) 604 { 605 strServer = "Server=127.0.0.0; DataBase=McsSP; user id=sqluser; password=Pass@word123;"; 606 } 607 using (System.Data.SqlClient.SqlConnection SqlCnn = new System.Data.SqlClient.SqlConnection(strServer)) 608 { 609 SqlCnn.Open(); 610 System.Data.SqlClient.SqlDataAdapter SqlDa = new System.Data.SqlClient.SqlDataAdapter(sql, SqlCnn); 611 DataSet DS = new DataSet(); 612 SqlDa.Fill(DS); 613 SqlDa.Dispose(); 614 SqlCnn.Close(); 615 if (DS == null || DS.Tables == null || DS.Tables.Count < 1) 616 return null; 617 dt = DS.Tables[0]; 618 } 619 return dt; 620 }
需要下载npoi dll