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 throw exception; 826 827 } 828 } 829 table.Rows.Add(dataRow); 830 } 831 catch (Exception exception) 832 { 833 throw exception; 834 } 835 } 836 } 837 catch (Exception exception) 838 { 839 throw exception; 840 } 841 return table; 842 } 843 844 #endregion 845 846 847 public static void InsertSheet(string outputFile, string sheetname, DataTable dt) 848 { 849 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 850 IWorkbook hssfworkbook = WorkbookFactory.Create(readfile); 851 //HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 852 int num = hssfworkbook.GetSheetIndex(sheetname); 853 ISheet sheet1; 854 if (num >= 0) 855 sheet1 = hssfworkbook.GetSheet(sheetname); 856 else 857 { 858 sheet1 = hssfworkbook.CreateSheet(sheetname); 859 } 860 861 862 try 863 { 864 if (sheet1.GetRow(0) == null) 865 { 866 sheet1.CreateRow(0); 867 } 868 for (int coluid = 0; coluid < dt.Columns.Count; coluid++) 869 { 870 if (sheet1.GetRow(0).GetCell(coluid) == null) 871 { 872 sheet1.GetRow(0).CreateCell(coluid); 873 } 874 875 sheet1.GetRow(0).GetCell(coluid).SetCellValue(dt.Columns[coluid].ColumnName); 876 } 877 } 878 catch (Exception ex) 879 { 880 throw ex; 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 throw ex; 905 } 906 } 907 try 908 { 909 readfile.Close(); 910 911 FileStream writefile = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.Write); 912 hssfworkbook.Write(writefile); 913 writefile.Close(); 914 } 915 catch (Exception ex) 916 { 917 throw ex; 918 } 919 } 920 921 #region 更新excel中的数据 922 /// <summary> 923 /// 更新Excel表格 924 /// </summary> 925 /// <param name="outputFile">需更新的excel表格路径</param> 926 /// <param name="sheetname">sheet名</param> 927 /// <param name="updateData">需更新的数据</param> 928 /// <param name="coluid">需更新的列号</param> 929 /// <param name="rowid">需更新的开始行号</param> 930 public static void UpdateExcel(string outputFile, string sheetname, string[] updateData, int coluid, int rowid) 931 { 932 //FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 933 IWorkbook hssfworkbook = null;// WorkbookFactory.Create(outputFile); 934 //HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 935 ISheet sheet1 = hssfworkbook.GetSheet(sheetname); 936 for (int i = 0; i < updateData.Length; i++) 937 { 938 try 939 { 940 if (sheet1.GetRow(i + rowid) == null) 941 { 942 sheet1.CreateRow(i + rowid); 943 } 944 if (sheet1.GetRow(i + rowid).GetCell(coluid) == null) 945 { 946 sheet1.GetRow(i + rowid).CreateCell(coluid); 947 } 948 949 sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]); 950 } 951 catch (Exception ex) 952 { 953 throw ex; 954 } 955 } 956 try 957 { 958 //readfile.Close(); 959 FileStream writefile = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.Write); 960 hssfworkbook.Write(writefile); 961 writefile.Close(); 962 } 963 catch (Exception ex) 964 { 965 throw ex; 966 } 967 968 } 969 970 /// <summary> 971 /// 更新Excel表格 972 /// </summary> 973 /// <param name="outputFile">需更新的excel表格路径</param> 974 /// <param name="sheetname">sheet名</param> 975 /// <param name="updateData">需更新的数据</param> 976 /// <param name="coluids">需更新的列号</param> 977 /// <param name="rowid">需更新的开始行号</param> 978 public static void UpdateExcel(string outputFile, string sheetname, string[][] updateData, int[] coluids, int rowid) 979 { 980 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 981 982 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 983 readfile.Close(); 984 ISheet sheet1 = hssfworkbook.GetSheet(sheetname); 985 for (int j = 0; j < coluids.Length; j++) 986 { 987 for (int i = 0; i < updateData[j].Length; i++) 988 { 989 try 990 { 991 if (sheet1.GetRow(i + rowid) == null) 992 { 993 sheet1.CreateRow(i + rowid); 994 } 995 if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null) 996 { 997 sheet1.GetRow(i + rowid).CreateCell(coluids[j]); 998 } 999 sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]); 1000 } 1001 catch (Exception ex) 1002 { 1003 throw ex; 1004 } 1005 } 1006 } 1007 try 1008 { 1009 FileStream writefile = new FileStream(outputFile, FileMode.Create); 1010 hssfworkbook.Write(writefile); 1011 writefile.Close(); 1012 } 1013 catch (Exception ex) 1014 { 1015 throw ex; 1016 } 1017 } 1018 1019 /// <summary> 1020 /// 更新Excel表格 1021 /// </summary> 1022 /// <param name="outputFile">需更新的excel表格路径</param> 1023 /// <param name="sheetname">sheet名</param> 1024 /// <param name="updateData">需更新的数据</param> 1025 /// <param name="coluid">需更新的列号</param> 1026 /// <param name="rowid">需更新的开始行号</param> 1027 public static void UpdateExcel(string outputFile, string sheetname, double[] updateData, int coluid, int rowid) 1028 { 1029 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 1030 1031 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 1032 ISheet sheet1 = hssfworkbook.GetSheet(sheetname); 1033 for (int i = 0; i < updateData.Length; i++) 1034 { 1035 try 1036 { 1037 if (sheet1.GetRow(i + rowid) == null) 1038 { 1039 sheet1.CreateRow(i + rowid); 1040 } 1041 if (sheet1.GetRow(i + rowid).GetCell(coluid) == null) 1042 { 1043 sheet1.GetRow(i + rowid).CreateCell(coluid); 1044 } 1045 1046 sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]); 1047 } 1048 catch (Exception ex) 1049 { 1050 throw ex; 1051 } 1052 } 1053 try 1054 { 1055 readfile.Close(); 1056 FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write); 1057 hssfworkbook.Write(writefile); 1058 writefile.Close(); 1059 } 1060 catch (Exception ex) 1061 { 1062 throw ex; 1063 } 1064 1065 } 1066 1067 /// <summary> 1068 /// 更新Excel表格 1069 /// </summary> 1070 /// <param name="outputFile">需更新的excel表格路径</param> 1071 /// <param name="sheetname">sheet名</param> 1072 /// <param name="updateData">需更新的数据</param> 1073 /// <param name="coluids">需更新的列号</param> 1074 /// <param name="rowid">需更新的开始行号</param> 1075 public static void UpdateExcel(string outputFile, string sheetname, double[][] updateData, int[] coluids, int rowid) 1076 { 1077 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 1078 1079 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 1080 readfile.Close(); 1081 ISheet sheet1 = hssfworkbook.GetSheet(sheetname); 1082 for (int j = 0; j < coluids.Length; j++) 1083 { 1084 for (int i = 0; i < updateData[j].Length; i++) 1085 { 1086 try 1087 { 1088 if (sheet1.GetRow(i + rowid) == null) 1089 { 1090 sheet1.CreateRow(i + rowid); 1091 } 1092 if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null) 1093 { 1094 sheet1.GetRow(i + rowid).CreateCell(coluids[j]); 1095 } 1096 sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]); 1097 } 1098 catch (Exception ex) 1099 { 1100 throw ex; 1101 } 1102 } 1103 } 1104 try 1105 { 1106 FileStream writefile = new FileStream(outputFile, FileMode.Create); 1107 hssfworkbook.Write(writefile); 1108 writefile.Close(); 1109 } 1110 catch (Exception ex) 1111 { 1112 throw ex; 1113 } 1114 } 1115 1116 #endregion 1117 1118 public static int GetSheetNumber(string outputFile) 1119 { 1120 int number = 0; 1121 try 1122 { 1123 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 1124 1125 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 1126 number = hssfworkbook.NumberOfSheets; 1127 1128 } 1129 catch (Exception exception) 1130 { 1131 throw exception; 1132 } 1133 return number; 1134 } 1135 1136 public static ArrayList GetSheetName(string outputFile) 1137 { 1138 ArrayList arrayList = new ArrayList(); 1139 try 1140 { 1141 FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); 1142 1143 HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile); 1144 for (int i = 0; i < hssfworkbook.NumberOfSheets; i++) 1145 { 1146 arrayList.Add(hssfworkbook.GetSheetName(i)); 1147 } 1148 } 1149 catch (Exception exception) 1150 { 1151 throw exception; 1152 } 1153 return arrayList; 1154 } 1155 1156 public static bool isNumeric(String message, out double result) 1157 { 1158 Regex rex = new Regex(@"^[-]?\d+[.]?\d*$"); 1159 result = -1; 1160 if (rex.IsMatch(message)) 1161 { 1162 result = double.Parse(message); 1163 return true; 1164 } 1165 else 1166 return false; 1167 1168 } 1169 1170 1171 1172 ////////// 现用导出 \\\\\\\\\\ 1173 /// <summary> 1174 /// 用于Web导出 第一步 1175 /// </summary> 1176 /// <param name="dtSource">源DataTable</param> 1177 /// <param name="strHeaderText">表头文本</param> 1178 /// <param name="strFileName">文件名</param> 1179 public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName) 1180 { 1181 HttpContext curContext = HttpContext.Current; 1182 1183 // 设置编码和附件格式 1184 curContext.Response.ContentType = "application/vnd.ms-excel"; 1185 curContext.Response.ContentEncoding = Encoding.UTF8; 1186 curContext.Response.Charset = ""; 1187 curContext.Response.AppendHeader("Content-Disposition", 1188 "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8)); 1189 1190 curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer()); 1191 curContext.Response.End(); 1192 } 1193 1194 1195 1196 /// <summary> 1197 /// DataTable导出到Excel的MemoryStream 第二步 1198 /// </summary> 1199 /// <param name="dtSource">源DataTable</param> 1200 /// <param name="strHeaderText">表头文本</param> 1201 public static MemoryStream Export(DataTable dtSource, string strHeaderText) 1202 { 1203 HSSFWorkbook workbook = new HSSFWorkbook(); 1204 HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet; 1205 1206 #region 右击文件 属性信息 1207 { 1208 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 1209 dsi.Company = "NPOI"; 1210 workbook.DocumentSummaryInformation = dsi; 1211 1212 SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); 1213 si.Author = "文件作者信息"; //填加xls文件作者信息 1214 si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息 1215 si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息 1216 si.Comments = "作者信息"; //填加xls文件作者信息 1217 si.Title = "标题信息"; //填加xls文件标题信息 1218 si.Subject = "主题信息";//填加文件主题信息 1219 1220 si.CreateDateTime = DateTime.Now; 1221 workbook.SummaryInformation = si; 1222 } 1223 #endregion 1224 1225 HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle; 1226 HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat; 1227 dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); 1228 1229 //取得列宽 1230 int[] arrColWidth = new int[dtSource.Columns.Count]; 1231 foreach (DataColumn item in dtSource.Columns) 1232 { 1233 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; 1234 } 1235 for (int i = 0; i < dtSource.Rows.Count; i++) 1236 { 1237 for (int j = 0; j < dtSource.Columns.Count; j++) 1238 { 1239 int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; 1240 if (intTemp > arrColWidth[j]) 1241 { 1242 arrColWidth[j] = intTemp; 1243 } 1244 } 1245 } 1246 int rowIndex = 0; 1247 foreach (DataRow row in dtSource.Rows) 1248 { 1249 #region 新建表,填充表头,填充列头,样式 1250 if (rowIndex == 65535 || rowIndex == 0) 1251 { 1252 if (rowIndex != 0) 1253 { 1254 sheet = workbook.CreateSheet() as HSSFSheet; 1255 } 1256 1257 #region 表头及样式 1258 { 1259 if (string.IsNullOrEmpty(strHeaderText)) 1260 { 1261 HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow; 1262 headerRow.HeightInPoints = 25; 1263 headerRow.CreateCell(0).SetCellValue(strHeaderText); 1264 HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle; 1265 //headStyle.Alignment = CellHorizontalAlignment.CENTER; 1266 HSSFFont font = workbook.CreateFont() as HSSFFont; 1267 font.FontHeightInPoints = 20; 1268 font.Boldweight = 700; 1269 headStyle.SetFont(font); 1270 headerRow.GetCell(0).CellStyle = headStyle; 1271 sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); 1272 //headerRow.Dispose(); 1273 } 1274 } 1275 #endregion 1276 1277 #region 列头及样式 1278 { 1279 HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow; 1280 HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle; 1281 //headStyle.Alignment = CellHorizontalAlignment.CENTER; 1282 HSSFFont font = workbook.CreateFont() as HSSFFont; 1283 font.FontHeightInPoints = 10; 1284 font.Boldweight = 700; 1285 headStyle.SetFont(font); 1286 foreach (DataColumn column in dtSource.Columns) 1287 { 1288 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); 1289 headerRow.GetCell(column.Ordinal).CellStyle = headStyle; 1290 1291 //设置列宽 1292 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 1293 } 1294 //headerRow.Dispose(); 1295 } 1296 #endregion 1297 1298 rowIndex = 1; 1299 } 1300 #endregion 1301 1302 1303 #region 填充内容 1304 HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow; 1305 foreach (DataColumn column in dtSource.Columns) 1306 { 1307 HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell; 1308 1309 string drValue = row[column].ToString(); 1310 1311 switch (column.DataType.ToString()) 1312 { 1313 case "System.String"://字符串类型 1314 newCell.SetCellValue(drValue); 1315 break; 1316 case "System.DateTime"://日期类型 1317 DateTime dateV; 1318 DateTime.TryParse(drValue, out dateV); 1319 newCell.SetCellValue(dateV); 1320 1321 newCell.CellStyle = dateStyle;//格式化显示 1322 break; 1323 case "System.Boolean"://布尔型 1324 bool boolV = false; 1325 bool.TryParse(drValue, out boolV); 1326 newCell.SetCellValue(boolV); 1327 break; 1328 case "System.Int16"://整型 1329 case "System.Int32": 1330 case "System.Int64": 1331 case "System.Byte": 1332 int intV = 0; 1333 int.TryParse(drValue, out intV); 1334 newCell.SetCellValue(intV); 1335 break; 1336 case "System.Decimal"://浮点型 1337 case "System.Double": 1338 double doubV = 0; 1339 double.TryParse(drValue, out doubV); 1340 newCell.SetCellValue(doubV); 1341 break; 1342 case "System.DBNull"://空值处理 1343 newCell.SetCellValue(""); 1344 break; 1345 default: 1346 newCell.SetCellValue(""); 1347 break; 1348 } 1349 } 1350 #endregion 1351 1352 rowIndex++; 1353 } 1354 using (MemoryStream ms = new MemoryStream()) 1355 { 1356 workbook.Write(ms); 1357 ms.Flush(); 1358 ms.Position = 0; 1359 1360 //sheet.Dispose(); 1361 //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet 1362 return ms; 1363 } 1364 } 1365 1366 /// <summary> 1367 /// /注:分浏览器进行编码(IE必须编码,FireFox不能编码,Chrome可编码也可不编码) 1368 /// </summary> 1369 /// <param name="ds"></param> 1370 /// <param name="strHeaderText"></param> 1371 /// <param name="strFileName"></param> 1372 public static void ExportByWeb(DataSet ds, string strHeaderText, string strFileName) 1373 { 1374 HttpContext curContext = HttpContext.Current; 1375 curContext.Response.ContentType = "application/vnd.ms-excel"; 1376 curContext.Response.Charset = ""; 1377 if (curContext.Request.UserAgent.ToLower().IndexOf("firefox", System.StringComparison.Ordinal) > 0) 1378 { 1379 curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + strFileName); 1380 } 1381 else 1382 { 1383 curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8)); 1384 } 1385 1386 // curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" +strFileName); 1387 curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); 1388 curContext.Response.BinaryWrite(ExportDataSetToExcel(ds, strHeaderText).GetBuffer()); 1389 curContext.Response.End(); 1390 } 1391 1392 /// <summary> 1393 /// 由DataSet导出Excel 1394 /// </summary> 1395 /// <param name="sourceTable">要导出数据的DataTable</param> 1396 /// <param name="sheetName">工作表名称</param> 1397 /// <returns>Excel工作表</returns> 1398 private static MemoryStream ExportDataSetToExcel(DataSet sourceDs, string sheetName) 1399 { 1400 HSSFWorkbook workbook = new HSSFWorkbook(); 1401 MemoryStream ms = new MemoryStream(); 1402 string[] sheetNames = sheetName.Split(‘,‘); 1403 for (int i = 0; i < sheetNames.Length; i++) 1404 { 1405 ISheet sheet = workbook.CreateSheet(sheetNames[i]); 1406 1407 #region 列头 1408 IRow headerRow = sheet.CreateRow(0); 1409 HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle; 1410 HSSFFont font = workbook.CreateFont() as HSSFFont; 1411 font.FontHeightInPoints = 10; 1412 font.Boldweight = 700; 1413 headStyle.SetFont(font); 1414 1415 //取得列宽 1416 int[] arrColWidth = new int[sourceDs.Tables[i].Columns.Count]; 1417 foreach (DataColumn item in sourceDs.Tables[i].Columns) 1418 { 1419 arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; 1420 } 1421 1422 // 处理列头 1423 foreach (DataColumn column in sourceDs.Tables[i].Columns) 1424 { 1425 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); 1426 headerRow.GetCell(column.Ordinal).CellStyle = headStyle; 1427 //设置列宽 1428 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); 1429 1430 } 1431 #endregion 1432 1433 #region 填充值 1434 int rowIndex = 1; 1435 foreach (DataRow row in sourceDs.Tables[i].Rows) 1436 { 1437 IRow dataRow = sheet.CreateRow(rowIndex); 1438 foreach (DataColumn column in sourceDs.Tables[i].Columns) 1439 { 1440 dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); 1441 } 1442 rowIndex++; 1443 } 1444 #endregion 1445 } 1446 workbook.Write(ms); 1447 ms.Flush(); 1448 ms.Position = 0; 1449 workbook = null; 1450 return ms; 1451 } 1452 1453 1454 /// <summary> 1455 /// 验证导入的Excel是否有数据 1456 /// </summary> 1457 /// <param name="excelFileStream"></param> 1458 /// <returns></returns> 1459 public static bool HasData(Stream excelFileStream) 1460 { 1461 using (excelFileStream) 1462 { 1463 IWorkbook workBook = new HSSFWorkbook(excelFileStream); 1464 if (workBook.NumberOfSheets > 0) 1465 { 1466 ISheet sheet = workBook.GetSheetAt(0); 1467 return sheet.PhysicalNumberOfRows > 0; 1468 } 1469 } 1470 return false; 1471 1472 }
时间: 2024-10-05 20:25:32