C#利用NPOI处理excel的类 NPOIHelper.cs
个人的NPOIHelp类,包括datatable导出到excel,dataset导出到excel,excel导入到datatable,excel导入到dataset,
更新excel中的数据,验证导入的Excel是否有数据等操作
1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.IO; 5 using System.Text; 6 using System.Web; 7 using NPOI; 8 using NPOI.HPSF; 9 using NPOI.HSSF; 10 using NPOI.HSSF.UserModel; 11 using NPOI.HSSF.Util; 12 using NPOI.POIFS; 13 using NPOI.SS.Formula.Eval; 14 using NPOI.SS.UserModel; 15 using NPOI.Util; 16 using NPOI.SS; 17 using NPOI.DDF; 18 using NPOI.SS.Util; 19 using System.Collections; 20 using System.Text.RegularExpressions; 21 using NPOI.XSSF; 22 using NPOI.XSSF.UserModel; 23 24 public class NPOIHelper 25 { 26 private static WriteLog wl = new WriteLog(); 27 28 29 #region 从datatable中将数据导出到excel 30 /// <summary> 31 /// DataTable导出到Excel的MemoryStream 32 /// </summary> 33 /// <param name="dtSource">源DataTable</param> 34 /// <param name="strHeaderText">表头文本</param> 35 static MemoryStream ExportDT(DataTable dtSource, string strHeaderText) 36 { 37 HSSFWorkbook workbook = new HSSFWorkbook(); 38 HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet; 39 40 #region 右击文件 属性信息 41 42 //{ 43 // DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 44 // dsi.Company = "http://www.yongfa365.com/"; 45 // workbook.DocumentSummaryInformation = dsi; 46 47 // SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); 48 // si.Author = "柳永法"; //填加xls文件作者信息 49 // si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息 50 // si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息 51 // si.Comments = "说明信息"; //填加xls文件作者信息 52 // si.Title = "NPOI测试"; //填加xls文件标题信息 53 // si.Subject = "NPOI测试Demo"; //填加文件主题信息 54 // si.CreateDateTime = DateTime.Now; 55 // workbook.SummaryInformation = si; 56 //} 57 58 #endregion 59 60 HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle; 61 HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat; 62 dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); 63 64 //取得列宽 65 int[] arrColWidth = new int[dtSource.Columns.Count]; 66 foreach (DataColumn item in dtSource.Columns) 67 { 68 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; 69 } 70 for (int i = 0; i < dtSource.Rows.Count; i++) 71 { 72 for (int j = 0; j < dtSource.Columns.Count; j++) 73 { 74 int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; 75 if (intTemp > arrColWidth[j]) 76 { 77 arrColWidth[j] = intTemp; 78 } 79 } 80 } 81 int rowIndex = 0; 82 83 foreach (DataRow row in dtSource.Rows) 84 { 85 #region 新建表,填充表头,填充列头,样式 86 87 if (rowIndex == 65535 || rowIndex == 0) 88 { 89 if (rowIndex != 0) 90 { 91 sheet = workbook.CreateSheet() as HSSFSheet; 92 } 93 94 #region 表头及样式 95 96 { 97 HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow; 98 headerRow.HeightInPoints = 25; 99 headerRow.CreateCell(0).SetCellValue(strHeaderText); 100 101 HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle; 102 headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER; 103 HSSFFont font = workbook.CreateFont() as HSSFFont; 104 font.FontHeightInPoints = 20; 105 font.Boldweight = 700; 106 headStyle.SetFont(font); 107 108 headerRow.GetCell(0).CellStyle = headStyle; 109 110 sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); 111 //headerRow.Dispose(); 112 } 113 114 #endregion 115 116 117 #region 列头及样式 118 119 { 120 HSSFRow headerRow = sheet.CreateRow(1) as HSSFRow; 121 122 123 HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle; 124 headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER; 125 HSSFFont font = workbook.CreateFont() as HSSFFont; 126 font.FontHeightInPoints = 10; 127 font.Boldweight = 700; 128 headStyle.SetFont(font); 129 130 131 foreach (DataColumn column in dtSource.Columns) 132 { 133 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); 134 headerRow.GetCell(column.Ordinal).CellStyle = headStyle; 135 136 //设置列宽 137 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 138 139 } 140 //headerRow.Dispose(); 141 } 142 143 #endregion 144 145 rowIndex = 2; 146 } 147 148 #endregion 149 150 #region 填充内容 151 152 HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow; 153 foreach (DataColumn column in dtSource.Columns) 154 { 155 HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell; 156 157 string drValue = row[column].ToString(); 158 159 switch (column.DataType.ToString()) 160 { 161 case "System.String": //字符串类型 162 double result; 163 if (isNumeric(drValue, out result)) 164 { 165 166 double.TryParse(drValue, out result); 167 newCell.SetCellValue(result); 168 break; 169 } 170 else 171 { 172 newCell.SetCellValue(drValue); 173 break; 174 } 175 176 case "System.DateTime": //日期类型 177 DateTime dateV; 178 DateTime.TryParse(drValue, out dateV); 179 newCell.SetCellValue(dateV); 180 181 newCell.CellStyle = dateStyle; //格式化显示 182 break; 183 case "System.Boolean": //布尔型 184 bool boolV = false; 185 bool.TryParse(drValue, out boolV); 186 newCell.SetCellValue(boolV); 187 break; 188 case "System.Int16": //整型 189 case "System.Int32": 190 case "System.Int64": 191 case "System.Byte": 192 int intV = 0; 193 int.TryParse(drValue, out intV); 194 newCell.SetCellValue(intV); 195 break; 196 case "System.Decimal": //浮点型 197 case "System.Double": 198 double doubV = 0; 199 double.TryParse(drValue, out doubV); 200 newCell.SetCellValue(doubV); 201 break; 202 case "System.DBNull": //空值处理 203 newCell.SetCellValue(""); 204 break; 205 default: 206 newCell.SetCellValue(""); 207 break; 208 } 209 210 } 211 212 #endregion 213 214 rowIndex++; 215 } 216 using (MemoryStream ms = new MemoryStream()) 217 { 218 workbook.Write(ms); 219 ms.Flush(); 220 ms.Position = 0; 221 222 //sheet.Dispose(); 223 //workbook.Dispose(); 224 225 return ms; 226 } 227 } 228 229 /// <summary> 230 /// DataTable导出到Excel的MemoryStream 231 /// </summary> 232 /// <param name="dtSource">源DataTable</param> 233 /// <param name="strHeaderText">表头文本</param> 234 static void ExportDTI(DataTable dtSource, string strHeaderText, FileStream fs) 235 { 236 XSSFWorkbook workbook = new XSSFWorkbook(); 237 XSSFSheet sheet = workbook.CreateSheet() as XSSFSheet; 238 239 #region 右击文件 属性信息 240 241 //{ 242 // DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 243 // dsi.Company = "http://www.yongfa365.com/"; 244 // workbook.DocumentSummaryInformation = dsi; 245 246 // SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); 247 // si.Author = "柳永法"; //填加xls文件作者信息 248 // si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息 249 // si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息 250 // si.Comments = "说明信息"; //填加xls文件作者信息 251 // si.Title = "NPOI测试"; //填加xls文件标题信息 252 // si.Subject = "NPOI测试Demo"; //填加文件主题信息 253 // si.CreateDateTime = DateTime.Now; 254 // workbook.SummaryInformation = si; 255 //} 256 257 #endregion 258 259 XSSFCellStyle dateStyle = workbook.CreateCellStyle() as XSSFCellStyle; 260 XSSFDataFormat format = workbook.CreateDataFormat() as XSSFDataFormat; 261 dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); 262 263 //取得列宽 264 int[] arrColWidth = new int[dtSource.Columns.Count]; 265 foreach (DataColumn item in dtSource.Columns) 266 { 267 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; 268 } 269 for (int i = 0; i < dtSource.Rows.Count; i++) 270 { 271 for (int j = 0; j < dtSource.Columns.Count; j++) 272 { 273 int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; 274 if (intTemp > arrColWidth[j]) 275 { 276 arrColWidth[j] = intTemp; 277 } 278 } 279 } 280 int rowIndex = 0; 281 282 foreach (DataRow row in dtSource.Rows) 283 { 284 #region 新建表,填充表头,填充列头,样式 285 286 if (rowIndex == 0) 287 { 288 #region 表头及样式 289 //{ 290 // XSSFRow headerRow = sheet.CreateRow(0) as XSSFRow; 291 // headerRow.HeightInPoints = 25; 292 // headerRow.CreateCell(0).SetCellValue(strHeaderText); 293 294 // XSSFCellStyle headStyle = workbook.CreateCellStyle() as XSSFCellStyle; 295 // headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER; 296 // XSSFFont font = workbook.CreateFont() as XSSFFont; 297 // font.FontHeightInPoints = 20; 298 // font.Boldweight = 700; 299 // headStyle.SetFont(font); 300 301 // headerRow.GetCell(0).CellStyle = headStyle; 302 303 // //sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); 304 // //headerRow.Dispose(); 305 //} 306 307 #endregion 308 309 310 #region 列头及样式 311 312 { 313 XSSFRow headerRow = sheet.CreateRow(0) as XSSFRow; 314 315 316 XSSFCellStyle headStyle = workbook.CreateCellStyle() as XSSFCellStyle; 317 headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER; 318 XSSFFont font = workbook.CreateFont() as XSSFFont; 319 font.FontHeightInPoints = 10; 320 font.Boldweight = 700; 321 headStyle.SetFont(font); 322 323 324 foreach (DataColumn column in dtSource.Columns) 325 { 326 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); 327 headerRow.GetCell(column.Ordinal).CellStyle = headStyle; 328 329 //设置列宽 330 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 331 332 } 333 //headerRow.Dispose(); 334 } 335 336 #endregion 337 338 rowIndex = 1; 339 } 340 341 #endregion 342 343 #region 填充内容 344 345 XSSFRow dataRow = sheet.CreateRow(rowIndex) as XSSFRow; 346 foreach (DataColumn column in dtSource.Columns) 347 { 348 XSSFCell newCell = dataRow.CreateCell(column.Ordinal) as XSSFCell; 349 350 string drValue = row[column].ToString(); 351 352 switch (column.DataType.ToString()) 353 { 354 case "System.String": //字符串类型 355 double result; 356 if (isNumeric(drValue, out result)) 357 { 358 359 double.TryParse(drValue, out result); 360 newCell.SetCellValue(result); 361 break; 362 } 363 else 364 { 365 newCell.SetCellValue(drValue); 366 break; 367 } 368 369 case "System.DateTime": //日期类型 370 DateTime dateV; 371 DateTime.TryParse(drValue, out dateV); 372 newCell.SetCellValue(dateV); 373 374 newCell.CellStyle = dateStyle; //格式化显示 375 break; 376 case "System.Boolean": //布尔型 377 bool boolV = false; 378 bool.TryParse(drValue, out boolV); 379 newCell.SetCellValue(boolV); 380 break; 381 case "System.Int16": //整型 382 case "System.Int32": 383 case "System.Int64": 384 case "System.Byte": 385 int intV = 0; 386 int.TryParse(drValue, out intV); 387 newCell.SetCellValue(intV); 388 break; 389 case "System.Decimal": //浮点型 390 case "System.Double": 391 double doubV = 0; 392 double.TryParse(drValue, out doubV); 393 newCell.SetCellValue(doubV); 394 break; 395 case "System.DBNull": //空值处理 396 newCell.SetCellValue(""); 397 break; 398 default: 399 newCell.SetCellValue(""); 400 break; 401 } 402 403 } 404 405 #endregion 406 407 rowIndex++; 408 } 409 workbook.Write(fs); 410 fs.Close(); 411 } 412 413 /// <summary> 414 /// DataTable导出到Excel文件 415 /// </summary> 416 /// <param name="dtSource">源DataTable</param> 417 /// <param name="strHeaderText">表头文本</param> 418 /// <param name="strFileName">保存位置</param> 419 public static void ExportDTtoExcel(DataTable dtSource, string strHeaderText, string strFileName) 420 { 421 string[] temp = strFileName.Split('.'); 422 423 if (temp[temp.Length - 1] == "xls" && dtSource.Columns.Count < 256 && dtSource.Rows.Count < 65536) 424 { 425 using (MemoryStream ms = ExportDT(dtSource, strHeaderText)) 426 { 427 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) 428 { 429 byte[] data = ms.ToArray(); 430 fs.Write(data, 0, data.Length); 431 fs.Flush(); 432 } 433 } 434 } 435 else 436 { 437 if (temp[temp.Length - 1] == "xls") 438 strFileName = strFileName + "x"; 439 440 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) 441 { 442 ExportDTI(dtSource, strHeaderText, fs); 443 } 444 } 445 } 446 #endregion 447 448 #region 从excel中将数据导出到datatable 449 /// <summary> 450 /// 读取excel 默认第一行为标头 451 /// </summary> 452 /// <param name="strFileName">excel文档路径</param> 453 /// <returns></returns> 454 public static DataTable ImportExceltoDt(string strFileName) 455 { 456 DataTable dt = new DataTable(); 457 IWorkbook wb; 458 using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) 459 { 460 wb = WorkbookFactory.Create(file); 461 } 462 ISheet sheet = wb.GetSheetAt(0); 463 dt = ImportDt(sheet, 0, true); 464 return dt; 465 } 466 467 /// <summary> 468 /// 读取Excel流到DataTable 469 /// </summary> 470 /// <param name="stream">Excel流</param> 471 /// <returns>第一个sheet中的数据</returns> 472 public static DataTable ImportExceltoDt(Stream stream) 473 { 474 try 475 { 476 DataTable dt = new DataTable(); 477 IWorkbook wb; 478 using (stream) 479 { 480 wb = WorkbookFactory.Create(stream); 481 } 482 ISheet sheet = wb.GetSheetAt(0); 483 dt = ImportDt(sheet, 0, true); 484 return dt; 485 } 486 catch (Exception) 487 { 488 489 throw; 490 } 491 } 492 493 /// <summary> 494 /// 读取Excel流到DataTable 495 /// </summary> 496 /// <param name="stream">Excel流</param> 497 /// <param name="sheetName">表单名</param> 498 /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param> 499 /// <returns>指定sheet中的数据</returns> 500 public static DataTable ImportExceltoDt(Stream stream, string sheetName, int HeaderRowIndex) 501 { 502 try 503 { 504 DataTable dt = new DataTable(); 505 IWorkbook wb; 506 using (stream) 507 { 508 wb = WorkbookFactory.Create(stream); 509 } 510 ISheet sheet = wb.GetSheet(sheetName); 511 dt = ImportDt(sheet, HeaderRowIndex, true); 512 return dt; 513 } 514 catch (Exception) 515 { 516 517 throw; 518 } 519 } 520 521 /// <summary> 522 /// 读取Excel流到DataSet 523 /// </summary> 524 /// <param name="stream">Excel流</param> 525 /// <returns>Excel中的数据</returns> 526 public static DataSet ImportExceltoDs(Stream stream) 527 { 528 try 529 { 530 DataSet ds = new DataSet(); 531 IWorkbook wb; 532 using (stream) 533 { 534 wb = WorkbookFactory.Create(stream); 535 } 536 for (int i = 0; i < wb.NumberOfSheets; i++) 537 { 538 DataTable dt = new DataTable(); 539 ISheet sheet = wb.GetSheetAt(i); 540 dt = ImportDt(sheet, 0, true); 541 ds.Tables.Add(dt); 542 } 543 return ds; 544 } 545 catch (Exception) 546 { 547 548 throw; 549 } 550 } 551 552 /// <summary> 553 /// 读取Excel流到DataSet 554 /// </summary> 555 /// <param name="stream">Excel流</param> 556 /// <param name="dict">字典参数,key:sheet名,value:列头所在行号,-1表示没有列头</param> 557 /// <returns>Excel中的数据</returns> 558 public static DataSet ImportExceltoDs(Stream stream,Dictionary<string,int> dict) 559 { 560 try 561 { 562 DataSet ds = new DataSet(); 563 IWorkbook wb; 564 using (stream) 565 { 566 wb = WorkbookFactory.Create(stream); 567 } 568 foreach (string key in dict.Keys) 569 { 570 DataTable dt = new DataTable(); 571 ISheet sheet = wb.GetSheet(key); 572 dt = ImportDt(sheet, dict[key], true); 573 ds.Tables.Add(dt); 574 } 575 return ds; 576 } 577 catch (Exception) 578 { 579 580 throw; 581 } 582 } 583 584 /// <summary> 585 /// 读取excel 586 /// </summary> 587 /// <param name="strFileName">excel文件路径</param> 588 /// <param name="sheet">需要导出的sheet</param> 589 /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param> 590 /// <returns></returns> 591 public static DataTable ImportExceltoDt(string strFileName, string SheetName, int HeaderRowIndex) 592 { 593 HSSFWorkbook workbook; 594 IWorkbook wb; 595 using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) 596 { 597 wb = new HSSFWorkbook(file); 598 } 599 ISheet sheet = wb.GetSheet(SheetName); 600 DataTable table = new DataTable(); 601 table = ImportDt(sheet, HeaderRowIndex, true); 602 //ExcelFileStream.Close(); 603 workbook = null; 604 sheet = null; 605 return table; 606 } 607 608 /// <summary> 609 /// 读取excel 610 /// </summary> 611 /// <param name="strFileName">excel文件路径</param> 612 /// <param name="sheet">需要导出的sheet序号</param> 613 /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param> 614 /// <returns></returns> 615 public static DataTable ImportExceltoDt(string strFileName, int SheetIndex, int HeaderRowIndex) 616 { 617 HSSFWorkbook workbook; 618 IWorkbook wb; 619 using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) 620 { 621 wb = WorkbookFactory.Create(file); 622 } 623 ISheet isheet = wb.GetSheetAt(SheetIndex); 624 DataTable table = new DataTable(); 625 table = ImportDt(isheet, HeaderRowIndex, true); 626 //ExcelFileStream.Close(); 627 workbook = null; 628 isheet = null; 629 return table; 630 } 631 632 /// <summary> 633 /// 读取excel 634 /// </summary> 635 /// <param name="strFileName">excel文件路径</param> 636 /// <param name="sheet">需要导出的sheet</param> 637 /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param> 638 /// <returns></returns> 639 public static DataTable ImportExceltoDt(string strFileName, string SheetName, int HeaderRowIndex, bool needHeader) 640 { 641 HSSFWorkbook workbook; 642 IWorkbook wb; 643 using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) 644 { 645 wb = WorkbookFactory.Create(file); 646 } 647 ISheet sheet = wb.GetSheet(SheetName); 648 DataTable table = new DataTable(); 649 table = ImportDt(sheet, HeaderRowIndex, needHeader); 650 //ExcelFileStream.Close(); 651 workbook = null; 652 sheet = null; 653 return table; 654 } 655 656 /// <summary> 657 /// 读取excel 658 /// </summary> 659 /// <param name="strFileName">excel文件路径</param> 660 /// <param name="sheet">需要导出的sheet序号</param> 661 /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param> 662 /// <returns></returns> 663 public static DataTable ImportExceltoDt(string strFileName, int SheetIndex, int HeaderRowIndex, bool needHeader) 664 { 665 HSSFWorkbook workbook; 666 IWorkbook wb; 667 using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) 668 { 669 wb = WorkbookFactory.Create(file); 670 } 671 ISheet sheet = wb.GetSheetAt(SheetIndex); 672 DataTable table = new DataTable(); 673 table = ImportDt(sheet, HeaderRowIndex, needHeader); 674 //ExcelFileStream.Close(); 675 workbook = null; 676 sheet = null; 677 return table; 678 } 679 680 /// <summary> 681 /// 将制定sheet中的数据导出到datatable中 682 /// </summary> 683 /// <param name="sheet">需要导出的sheet</param> 684 /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param> 685 /// <returns></returns> 686 static DataTable ImportDt(ISheet sheet, int HeaderRowIndex, bool needHeader) 687 { 688 DataTable table = new DataTable(); 689 IRow headerRow; 690 int cellCount; 691 try 692 { 693 if (HeaderRowIndex < 0 || !needHeader) 694 { 695 headerRow = sheet.GetRow(0); 696 cellCount = headerRow.LastCellNum; 697 698 for (int i = headerRow.FirstCellNum; i <= cellCount; i++) 699 { 700 DataColumn column = new DataColumn(Convert.ToString(i)); 701 table.Columns.Add(column); 702 } 703 } 704 else 705 { 706 headerRow = sheet.GetRow(HeaderRowIndex); 707 cellCount = headerRow.LastCellNum; 708 709 for (int i = headerRow.FirstCellNum; i <= cellCount; i++) 710 { 711 if (headerRow.GetCell(i) == null) 712 { 713 if (table.Columns.IndexOf(Convert.ToString(i)) > 0) 714 { 715 DataColumn column = new DataColumn(Convert.ToString("重复列名" + i)); 716 table.Columns.Add(column); 717 } 718 else 719 { 720 DataColumn column = new DataColumn(Convert.ToString(i)); 721 table.Columns.Add(column); 722 } 723 724 } 725 else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > 0) 726 { 727 DataColumn column = new DataColumn(Convert.ToString("重复列名" + i)); 728 table.Columns.Add(column); 729 } 730 else 731 { 732 DataColumn column = new DataColumn(headerRow.GetCell(i).ToString()); 733 table.Columns.Add(column); 734 } 735 } 736 } 737 int rowCount = sheet.LastRowNum; 738 for (int i = (HeaderRowIndex + 1); i <= sheet.LastRowNum; i++) 739 { 740 try 741 { 742 IRow row; 743 if (sheet.GetRow(i) == null) 744 { 745 row = sheet.CreateRow(i); 746 } 747 else 748 { 749 row = sheet.GetRow(i); 750 } 751 752 DataRow dataRow = table.NewRow(); 753 754 for (int j = row.FirstCellNum; j <= cellCount; j++) 755 { 756 try 757 { 758 if (row.GetCell(j) != null) 759 { 760 switch (row.GetCell(j).CellType) 761 { 762 case CellType.STRING: 763 string str = row.GetCell(j).StringCellValue; 764 if (str != null && str.Length > 0) 765 { 766 dataRow[j] = str.ToString(); 767 } 768 else 769 { 770 dataRow[j] = null; 771 } 772 break; 773 case CellType.NUMERIC: 774 if (DateUtil.IsCellDateFormatted(row.GetCell(j))) 775 { 776 dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue); 777 } 778 else 779 { 780 dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue); 781 } 782 break; 783 case CellType.BOOLEAN: 784 dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue); 785 break; 786 case CellType.ERROR: 787 dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue); 788 break; 789 case CellType.FORMULA: 790 switch (row.GetCell(j).CachedFormulaResultType) 791 { 792 case CellType.STRING: 793 string strFORMULA = row.GetCell(j).StringCellValue; 794 if (strFORMULA != null && strFORMULA.Length > 0) 795 { 796 dataRow[j] = strFORMULA.ToString(); 797 } 798 else 799 { 800 dataRow[j] = null; 801 } 802 break; 803 case CellType.NUMERIC: 804 dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue); 805 break; 806 case CellType.BOOLEAN: 807 dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue); 808 break; 809 case CellType.ERROR: 810 dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue); 811 break; 812 default: 813 dataRow[j] = ""; 814 break; 815 } 816 break; 817 default: 818 dataRow[j] = ""; 819 break; 820 } 821 } 822 } 823 catch (Exception exception) 824 { 825 wl.WriteLogs(exception.ToString()); 826 } 827 } 828 table.Rows.Add(dataRow); 829 } 830 catch (Exception exception) 831 { 832 wl.WriteLogs(exception.ToString()); 833 } 834 } 835 } 836 catch (Exception exception) 837 { 838 wl.WriteLogs(exception.ToString()); 839 } 840 return table; 841 } 842 843 #endregion 844 845 846 public static void InsertSheet(string outputFile, string sheetname, DataTable dt) 847 { 848 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 849 IWorkbook hssfworkbook = WorkbookFactory.Create(readfile); 850 //HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 851 int num = hssfworkbook.GetSheetIndex(sheetname); 852 ISheet sheet1; 853 if (num >= 0) 854 sheet1 = hssfworkbook.GetSheet(sheetname); 855 else 856 { 857 sheet1 = hssfworkbook.CreateSheet(sheetname); 858 } 859 860 861 try 862 { 863 if (sheet1.GetRow(0) == null) 864 { 865 sheet1.CreateRow(0); 866 } 867 for (int coluid = 0; coluid < dt.Columns.Count; coluid++) 868 { 869 if (sheet1.GetRow(0).GetCell(coluid) == null) 870 { 871 sheet1.GetRow(0).CreateCell(coluid); 872 } 873 874 sheet1.GetRow(0).GetCell(coluid).SetCellValue(dt.Columns[coluid].ColumnName); 875 } 876 } 877 catch (Exception ex) 878 { 879 wl.WriteLogs(ex.ToString()); 880 throw; 881 } 882 883 884 for (int i = 1; i <= dt.Rows.Count; i++) 885 { 886 try 887 { 888 if (sheet1.GetRow(i) == null) 889 { 890 sheet1.CreateRow(i); 891 } 892 for (int coluid = 0; coluid < dt.Columns.Count; coluid++) 893 { 894 if (sheet1.GetRow(i).GetCell(coluid) == null) 895 { 896 sheet1.GetRow(i).CreateCell(coluid); 897 } 898 899 sheet1.GetRow(i).GetCell(coluid).SetCellValue(dt.Rows[i - 1][coluid].ToString()); 900 } 901 } 902 catch (Exception ex) 903 { 904 wl.WriteLogs(ex.ToString()); 905 //throw; 906 } 907 } 908 try 909 { 910 readfile.Close(); 911 912 FileStream writefile = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.Write); 913 hssfworkbook.Write(writefile); 914 writefile.Close(); 915 } 916 catch (Exception ex) 917 { 918 wl.WriteLogs(ex.ToString()); 919 } 920 } 921 922 #region 更新excel中的数据 923 /// <summary> 924 /// 更新Excel表格 925 /// </summary> 926 /// <param name="outputFile">需更新的excel表格路径</param> 927 /// <param name="sheetname">sheet名</param> 928 /// <param name="updateData">需更新的数据</param> 929 /// <param name="coluid">需更新的列号</param> 930 /// <param name="rowid">需更新的开始行号</param> 931 public static void UpdateExcel(string outputFile, string sheetname, string[] updateData, int coluid, int rowid) 932 { 933 //FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 934 IWorkbook hssfworkbook = null;// WorkbookFactory.Create(outputFile); 935 //HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 936 ISheet sheet1 = hssfworkbook.GetSheet(sheetname); 937 for (int i = 0; i < updateData.Length; i++) 938 { 939 try 940 { 941 if (sheet1.GetRow(i + rowid) == null) 942 { 943 sheet1.CreateRow(i + rowid); 944 } 945 if (sheet1.GetRow(i + rowid).GetCell(coluid) == null) 946 { 947 sheet1.GetRow(i + rowid).CreateCell(coluid); 948 } 949 950 sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]); 951 } 952 catch (Exception ex) 953 { 954 wl.WriteLogs(ex.ToString()); 955 throw; 956 } 957 } 958 try 959 { 960 //readfile.Close(); 961 FileStream writefile = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.Write); 962 hssfworkbook.Write(writefile); 963 writefile.Close(); 964 } 965 catch (Exception ex) 966 { 967 wl.WriteLogs(ex.ToString()); 968 } 969 970 } 971 972 /// <summary> 973 /// 更新Excel表格 974 /// </summary> 975 /// <param name="outputFile">需更新的excel表格路径</param> 976 /// <param name="sheetname">sheet名</param> 977 /// <param name="updateData">需更新的数据</param> 978 /// <param name="coluids">需更新的列号</param> 979 /// <param name="rowid">需更新的开始行号</param> 980 public static void UpdateExcel(string outputFile, string sheetname, string[][] updateData, int[] coluids, int rowid) 981 { 982 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 983 984 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 985 readfile.Close(); 986 ISheet sheet1 = hssfworkbook.GetSheet(sheetname); 987 for (int j = 0; j < coluids.Length; j++) 988 { 989 for (int i = 0; i < updateData[j].Length; i++) 990 { 991 try 992 { 993 if (sheet1.GetRow(i + rowid) == null) 994 { 995 sheet1.CreateRow(i + rowid); 996 } 997 if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null) 998 { 999 sheet1.GetRow(i + rowid).CreateCell(coluids[j]); 1000 } 1001 sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]); 1002 } 1003 catch (Exception ex) 1004 { 1005 wl.WriteLogs(ex.ToString()); 1006 } 1007 } 1008 } 1009 try 1010 { 1011 FileStream writefile = new FileStream(outputFile, FileMode.Create); 1012 hssfworkbook.Write(writefile); 1013 writefile.Close(); 1014 } 1015 catch (Exception ex) 1016 { 1017 wl.WriteLogs(ex.ToString()); 1018 } 1019 } 1020 1021 /// <summary> 1022 /// 更新Excel表格 1023 /// </summary> 1024 /// <param name="outputFile">需更新的excel表格路径</param> 1025 /// <param name="sheetname">sheet名</param> 1026 /// <param name="updateData">需更新的数据</param> 1027 /// <param name="coluid">需更新的列号</param> 1028 /// <param name="rowid">需更新的开始行号</param> 1029 public static void UpdateExcel(string outputFile, string sheetname, double[] updateData, int coluid, int rowid) 1030 { 1031 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 1032 1033 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 1034 ISheet sheet1 = hssfworkbook.GetSheet(sheetname); 1035 for (int i = 0; i < updateData.Length; i++) 1036 { 1037 try 1038 { 1039 if (sheet1.GetRow(i + rowid) == null) 1040 { 1041 sheet1.CreateRow(i + rowid); 1042 } 1043 if (sheet1.GetRow(i + rowid).GetCell(coluid) == null) 1044 { 1045 sheet1.GetRow(i + rowid).CreateCell(coluid); 1046 } 1047 1048 sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]); 1049 } 1050 catch (Exception ex) 1051 { 1052 wl.WriteLogs(ex.ToString()); 1053 throw; 1054 } 1055 } 1056 try 1057 { 1058 readfile.Close(); 1059 FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write); 1060 hssfworkbook.Write(writefile); 1061 writefile.Close(); 1062 } 1063 catch (Exception ex) 1064 { 1065 wl.WriteLogs(ex.ToString()); 1066 } 1067 1068 } 1069 1070 /// <summary> 1071 /// 更新Excel表格 1072 /// </summary> 1073 /// <param name="outputFile">需更新的excel表格路径</param> 1074 /// <param name="sheetname">sheet名</param> 1075 /// <param name="updateData">需更新的数据</param> 1076 /// <param name="coluids">需更新的列号</param> 1077 /// <param name="rowid">需更新的开始行号</param> 1078 public static void UpdateExcel(string outputFile, string sheetname, double[][] updateData, int[] coluids, int rowid) 1079 { 1080 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 1081 1082 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 1083 readfile.Close(); 1084 ISheet sheet1 = hssfworkbook.GetSheet(sheetname); 1085 for (int j = 0; j < coluids.Length; j++) 1086 { 1087 for (int i = 0; i < updateData[j].Length; i++) 1088 { 1089 try 1090 { 1091 if (sheet1.GetRow(i + rowid) == null) 1092 { 1093 sheet1.CreateRow(i + rowid); 1094 } 1095 if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null) 1096 { 1097 sheet1.GetRow(i + rowid).CreateCell(coluids[j]); 1098 } 1099 sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]); 1100 } 1101 catch (Exception ex) 1102 { 1103 wl.WriteLogs(ex.ToString()); 1104 } 1105 } 1106 } 1107 try 1108 { 1109 FileStream writefile = new FileStream(outputFile, FileMode.Create); 1110 hssfworkbook.Write(writefile); 1111 writefile.Close(); 1112 } 1113 catch (Exception ex) 1114 { 1115 wl.WriteLogs(ex.ToString()); 1116 } 1117 } 1118 1119 #endregion 1120 1121 public static int GetSheetNumber(string outputFile) 1122 { 1123 int number = 0; 1124 try 1125 { 1126 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 1127 1128 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 1129 number = hssfworkbook.NumberOfSheets; 1130 1131 } 1132 catch (Exception exception) 1133 { 1134 wl.WriteLogs(exception.ToString()); 1135 } 1136 return number; 1137 } 1138 1139 public static ArrayList GetSheetName(string outputFile) 1140 { 1141 ArrayList arrayList = new ArrayList(); 1142 try 1143 { 1144 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 1145 1146 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 1147 for (int i = 0; i < hssfworkbook.NumberOfSheets; i++) 1148 { 1149 arrayList.Add(hssfworkbook.GetSheetName(i)); 1150 } 1151 } 1152 catch (Exception exception) 1153 { 1154 wl.WriteLogs(exception.ToString()); 1155 } 1156 return arrayList; 1157 } 1158 1159 public static bool isNumeric(String message, out double result) 1160 { 1161 Regex rex = new Regex(@"^[-]?\d+[.]?\d*$"); 1162 result = -1; 1163 if (rex.IsMatch(message)) 1164 { 1165 result = double.Parse(message); 1166 return true; 1167 } 1168 else 1169 return false; 1170 1171 } 1172 1173 1174 1175 ////////// 现用导出 \\\\\\\\\\ 1176 /// <summary> 1177 /// 用于Web导出 第一步 1178 /// </summary> 1179 /// <param name="dtSource">源DataTable</param> 1180 /// <param name="strHeaderText">表头文本</param> 1181 /// <param name="strFileName">文件名</param> 1182 public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName) 1183 { 1184 HttpContext curContext = HttpContext.Current; 1185 1186 // 设置编码和附件格式 1187 curContext.Response.ContentType = "application/vnd.ms-excel"; 1188 curContext.Response.ContentEncoding = Encoding.UTF8; 1189 curContext.Response.Charset = ""; 1190 curContext.Response.AppendHeader("Content-Disposition", 1191 "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8)); 1192 1193 curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer()); 1194 curContext.Response.End(); 1195 } 1196 1197 1198 1199 /// <summary> 1200 /// DataTable导出到Excel的MemoryStream 第二步 1201 /// </summary> 1202 /// <param name="dtSource">源DataTable</param> 1203 /// <param name="strHeaderText">表头文本</param> 1204 public static MemoryStream Export(DataTable dtSource, string strHeaderText) 1205 { 1206 HSSFWorkbook workbook = new HSSFWorkbook(); 1207 HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet; 1208 1209 #region 右击文件 属性信息 1210 { 1211 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 1212 dsi.Company = "NPOI"; 1213 workbook.DocumentSummaryInformation = dsi; 1214 1215 SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); 1216 si.Author = "文件作者信息"; //填加xls文件作者信息 1217 si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息 1218 si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息 1219 si.Comments = "作者信息"; //填加xls文件作者信息 1220 si.Title = "标题信息"; //填加xls文件标题信息 1221 si.Subject = "主题信息";//填加文件主题信息 1222 1223 si.CreateDateTime = DateTime.Now; 1224 workbook.SummaryInformation = si; 1225 } 1226 #endregion 1227 1228 HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle; 1229 HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat; 1230 dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); 1231 1232 //取得列宽 1233 int[] arrColWidth = new int[dtSource.Columns.Count]; 1234 foreach (DataColumn item in dtSource.Columns) 1235 { 1236 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; 1237 } 1238 for (int i = 0; i < dtSource.Rows.Count; i++) 1239 { 1240 for (int j = 0; j < dtSource.Columns.Count; j++) 1241 { 1242 int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; 1243 if (intTemp > arrColWidth[j]) 1244 { 1245 arrColWidth[j] = intTemp; 1246 } 1247 } 1248 } 1249 int rowIndex = 0; 1250 foreach (DataRow row in dtSource.Rows) 1251 { 1252 #region 新建表,填充表头,填充列头,样式 1253 if (rowIndex == 65535 || rowIndex == 0) 1254 { 1255 if (rowIndex != 0) 1256 { 1257 sheet = workbook.CreateSheet() as HSSFSheet; 1258 } 1259 1260 #region 表头及样式 1261 { 1262 if (string.IsNullOrEmpty(strHeaderText)) 1263 { 1264 HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow; 1265 headerRow.HeightInPoints = 25; 1266 headerRow.CreateCell(0).SetCellValue(strHeaderText); 1267 HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle; 1268 //headStyle.Alignment = CellHorizontalAlignment.CENTER; 1269 HSSFFont font = workbook.CreateFont() as HSSFFont; 1270 font.FontHeightInPoints = 20; 1271 font.Boldweight = 700; 1272 headStyle.SetFont(font); 1273 headerRow.GetCell(0).CellStyle = headStyle; 1274 sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); 1275 //headerRow.Dispose(); 1276 } 1277 } 1278 #endregion 1279 1280 #region 列头及样式 1281 { 1282 HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow; 1283 HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle; 1284 //headStyle.Alignment = CellHorizontalAlignment.CENTER; 1285 HSSFFont font = workbook.CreateFont() as HSSFFont; 1286 font.FontHeightInPoints = 10; 1287 font.Boldweight = 700; 1288 headStyle.SetFont(font); 1289 foreach (DataColumn column in dtSource.Columns) 1290 { 1291 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); 1292 headerRow.GetCell(column.Ordinal).CellStyle = headStyle; 1293 1294 //设置列宽 1295 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 1296 } 1297 //headerRow.Dispose(); 1298 } 1299 #endregion 1300 1301 rowIndex = 1; 1302 } 1303 #endregion 1304 1305 1306 #region 填充内容 1307 HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow; 1308 foreach (DataColumn column in dtSource.Columns) 1309 { 1310 HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell; 1311 1312 string drValue = row[column].ToString(); 1313 1314 switch (column.DataType.ToString()) 1315 { 1316 case "System.String"://字符串类型 1317 newCell.SetCellValue(drValue); 1318 break; 1319 case "System.DateTime"://日期类型 1320 DateTime dateV; 1321 DateTime.TryParse(drValue, out dateV); 1322 newCell.SetCellValue(dateV); 1323 1324 newCell.CellStyle = dateStyle;//格式化显示 1325 break; 1326 case "System.Boolean"://布尔型 1327 bool boolV = false; 1328 bool.TryParse(drValue, out boolV); 1329 newCell.SetCellValue(boolV); 1330 break; 1331 case "System.Int16"://整型 1332 case "System.Int32": 1333 case "System.Int64": 1334 case "System.Byte": 1335 int intV = 0; 1336 int.TryParse(drValue, out intV); 1337 newCell.SetCellValue(intV); 1338 break; 1339 case "System.Decimal"://浮点型 1340 case "System.Double": 1341 double doubV = 0; 1342 double.TryParse(drValue, out doubV); 1343 newCell.SetCellValue(doubV); 1344 break; 1345 case "System.DBNull"://空值处理 1346 newCell.SetCellValue(""); 1347 break; 1348 default: 1349 newCell.SetCellValue(""); 1350 break; 1351 } 1352 } 1353 #endregion 1354 1355 rowIndex++; 1356 } 1357 using (MemoryStream ms = new MemoryStream()) 1358 { 1359 workbook.Write(ms); 1360 ms.Flush(); 1361 ms.Position = 0; 1362 1363 //sheet.Dispose(); 1364 //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet 1365 return ms; 1366 } 1367 } 1368 1369 /// <summary> 1370 /// /注:分浏览器进行编码(IE必须编码,FireFox不能编码,Chrome可编码也可不编码) 1371 /// </summary> 1372 /// <param name="ds"></param> 1373 /// <param name="strHeaderText"></param> 1374 /// <param name="strFileName"></param> 1375 public static void ExportByWeb(DataSet ds, string strHeaderText, string strFileName) 1376 { 1377 HttpContext curContext = HttpContext.Current; 1378 curContext.Response.ContentType = "application/vnd.ms-excel"; 1379 curContext.Response.Charset = ""; 1380 if (curContext.Request.UserAgent.ToLower().IndexOf("firefox", System.StringComparison.Ordinal) > 0) 1381 { 1382 curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + strFileName); 1383 } 1384 else 1385 { 1386 curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8)); 1387 } 1388 1389 // curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" +strFileName); 1390 curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); 1391 curContext.Response.BinaryWrite(ExportDataSetToExcel(ds, strHeaderText).GetBuffer()); 1392 curContext.Response.End(); 1393 } 1394 1395 /// <summary> 1396 /// 由DataSet导出Excel 1397 /// </summary> 1398 /// <param name="sourceTable">要导出数据的DataTable</param> 1399 /// <param name="sheetName">工作表名称</param> 1400 /// <returns>Excel工作表</returns> 1401 private static MemoryStream ExportDataSetToExcel(DataSet sourceDs, string sheetName) 1402 { 1403 HSSFWorkbook workbook = new HSSFWorkbook(); 1404 MemoryStream ms = new MemoryStream(); 1405 string[] sheetNames = sheetName.Split(','); 1406 for (int i = 0; i < sheetNames.Length; i++) 1407 { 1408 ISheet sheet = workbook.CreateSheet(sheetNames[i]); 1409 1410 #region 列头 1411 IRow headerRow = sheet.CreateRow(0); 1412 HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle; 1413 HSSFFont font = workbook.CreateFont() as HSSFFont; 1414 font.FontHeightInPoints = 10; 1415 font.Boldweight = 700; 1416 headStyle.SetFont(font); 1417 1418 //取得列宽 1419 int[] arrColWidth = new int[sourceDs.Tables[i].Columns.Count]; 1420 foreach (DataColumn item in sourceDs.Tables[i].Columns) 1421 { 1422 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; 1423 } 1424 1425 // 处理列头 1426 foreach (DataColumn column in sourceDs.Tables[i].Columns) 1427 { 1428 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); 1429 headerRow.GetCell(column.Ordinal).CellStyle = headStyle; 1430 //设置列宽 1431 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 1432 1433 } 1434 #endregion 1435 1436 #region 填充值 1437 int rowIndex = 1; 1438 foreach (DataRow row in sourceDs.Tables[i].Rows) 1439 { 1440 IRow dataRow = sheet.CreateRow(rowIndex); 1441 foreach (DataColumn column in sourceDs.Tables[i].Columns) 1442 { 1443 dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); 1444 } 1445 rowIndex++; 1446 } 1447 #endregion 1448 } 1449 workbook.Write(ms); 1450 ms.Flush(); 1451 ms.Position = 0; 1452 workbook = null; 1453 return ms; 1454 } 1455 1456 1457 /// <summary> 1458 /// 验证导入的Excel是否有数据 1459 /// </summary> 1460 /// <param name="excelFileStream"></param> 1461 /// <returns></returns> 1462 public static bool HasData(Stream excelFileStream) 1463 { 1464 using (excelFileStream) 1465 { 1466 IWorkbook workBook = new HSSFWorkbook(excelFileStream); 1467 if (workBook.NumberOfSheets > 0) 1468 { 1469 ISheet sheet = workBook.GetSheetAt(0); 1470 return sheet.PhysicalNumberOfRows > 0; 1471 } 1472 } 1473 return false; 1474 } 1475 }
微信公众号:
Randy的技术笔记
如果您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】
如果您希望与我交流互动,欢迎关注微信公众号
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。