1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
|
public class ExcelHelper { #region Excel导出方法 ExcelDownload public static void ExcelDownload(DataTable dtSource, ExcelConfig excelConfig) { HttpContext curContext = HttpContext.Current; curContext.Response.ContentType = "application/ms-excel"; curContext.Response.ContentEncoding = Encoding.UTF8; curContext.Response.Charset = ""; curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(excelConfig.FileName, Encoding.UTF8)); curContext.Response.BinaryWrite(ExportMemoryStream(dtSource, excelConfig).GetBuffer()); curContext.Response.End(); } public static void ExcelDownload(List<TemplateDataModel> list, string templdateName, string newFileName) { HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.Charset = "UTF-8"; response.ContentType = "application/vnd-excel"; System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + newFileName)); System.Web.HttpContext.Current.Response.BinaryWrite(ExportListByTempale(list, templdateName).ToArray()); } #endregion
#region DataTable导出到Excel文件excelConfig中FileName设置为全路径 public static void ExcelExport(DataTable dtSource, ExcelConfig excelConfig) { using (MemoryStream ms = ExportMemoryStream(dtSource, excelConfig)) { using (FileStream fs = new FileStream(excelConfig.FileName, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } } } #endregion
#region DataTable导出到Excel的MemoryStream public static MemoryStream ExportMemoryStream(DataTable dtSource, ExcelConfig excelConfig) { DataTable dt = dtSource.Clone(); var columns = dt.Columns; foreach (DataColumn column in columns) { bool v = excelConfig.ColumnEntity.Exists(t => t.Column == column.ColumnName); if (!v) { dtSource.Columns.Remove(column.ColumnName); } }
HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(); #region 右击文件 属性信息 { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "NPOI"; workbook.DocumentSummaryInformation = dsi;
SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Author = "刘晓雷"; si.ApplicationName = "力软信息"; si.LastAuthor = "刘晓雷"; si.Comments = "刘晓雷"; si.Title = "标题信息"; si.Subject = "主题信息"; si.CreateDateTime = System.DateTime.Now; workbook.SummaryInformation = si; } #endregion
#region 设置标题样式 ICellStyle headStyle = workbook.CreateCellStyle(); int[] arrColWidth = new int[dtSource.Columns.Count]; string[] arrColName = new string[dtSource.Columns.Count]; ICellStyle[] arryColumStyle = new ICellStyle[dtSource.Columns.Count]; headStyle.Alignment = HorizontalAlignment.Center; if (excelConfig.Background != new Color()) { if (excelConfig.Background != new Color()) { headStyle.FillPattern = FillPattern.SolidForeground; headStyle.FillForegroundColor = GetXLColour(workbook, excelConfig.Background); } } IFont font = workbook.CreateFont(); font.FontHeightInPoints = excelConfig.TitlePoint; if (excelConfig.ForeColor != new Color()) { font.Color = GetXLColour(workbook, excelConfig.ForeColor); } font.Boldweight = 700; headStyle.SetFont(font); #endregion
#region 列头及样式 ICellStyle cHeadStyle = workbook.CreateCellStyle(); cHeadStyle.Alignment = HorizontalAlignment.Center; IFont cfont = workbook.CreateFont(); cfont.FontHeightInPoints = excelConfig.HeadPoint; cHeadStyle.SetFont(cfont); #endregion
#region 设置内容单元格样式 foreach (DataColumn item in dtSource.Columns) { ICellStyle columnStyle = workbook.CreateCellStyle(); columnStyle.Alignment = HorizontalAlignment.Center; arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; arrColName[item.Ordinal] = item.ColumnName.ToString(); if (excelConfig.ColumnEntity != null) { ColumnModel columnentity = excelConfig.ColumnEntity.Find(t => t.Column == item.ColumnName); if (columnentity != null) { arrColName[item.Ordinal] = columnentity.ExcelColumn; if (columnentity.Width != 0) { arrColWidth[item.Ordinal] = columnentity.Width; } if (columnentity.Background != new Color()) { if (columnentity.Background != new Color()) { columnStyle.FillPattern = FillPattern.SolidForeground; columnStyle.FillForegroundColor = GetXLColour(workbook, columnentity.Background); } } if (columnentity.Font != null || columnentity.Point != 0 || columnentity.ForeColor != new Color()) { IFont columnFont = workbook.CreateFont(); columnFont.FontHeightInPoints = 10; if (columnentity.Font != null) { columnFont.FontName = columnentity.Font; } if (columnentity.Point != 0) { columnFont.FontHeightInPoints = columnentity.Point; } if (columnentity.ForeColor != new Color()) { columnFont.Color = GetXLColour(workbook, columnentity.ForeColor); } columnStyle.SetFont(font); } columnStyle.Alignment = getAlignment(columnentity.Alignment); } } arryColumStyle[item.Ordinal] = columnStyle; } if (excelConfig.IsAllSizeColumn) { #region 根据列中最长列的长度取得列宽 for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { if (arrColWidth[j] != 0) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } }
} } #endregion } #endregion
int rowIndex = 0;
#region 表头及样式 if (excelConfig.Title != null) { IRow headerRow = sheet.CreateRow(rowIndex); rowIndex++; if (excelConfig.TitleHeight != 0) { headerRow.Height = (short)(excelConfig.TitleHeight * 20); } headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(excelConfig.Title); headerRow.GetCell(0).CellStyle = headStyle; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); } #endregion
#region 列头及样式 { IRow headerRow = sheet.CreateRow(rowIndex); rowIndex++; #region 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出 foreach (DataColumn column in dtSource.Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(arrColName[column.Ordinal]); headerRow.GetCell(column.Ordinal).CellStyle = cHeadStyle;
int colWidth = (arrColWidth[column.Ordinal] + 1) * 256; if (colWidth < 255 * 256) { sheet.SetColumnWidth(column.Ordinal, colWidth < 5000 ? 5000 : colWidth); } else { sheet.SetColumnWidth(column.Ordinal, 6000); } } #endregion } #endregion
ICellStyle dateStyle = workbook.CreateCellStyle(); IDataFormat format = workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); bool isStyle = false; ICellStyle rowStyle = workbook.CreateCellStyle(); foreach (DataRow row in dtSource.Rows) { #region 新建表,填充表头,填充列头,样式 if (rowIndex == 65535) { sheet = workbook.CreateSheet(); rowIndex = 0; #region 表头及样式 { if (excelConfig.Title != null) { IRow headerRow = sheet.CreateRow(rowIndex); rowIndex++; if (excelConfig.TitleHeight != 0) { headerRow.Height = (short)(excelConfig.TitleHeight * 20); } headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(excelConfig.Title); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); }
} #endregion
#region 列头及样式 { IRow headerRow = sheet.CreateRow(rowIndex); rowIndex++; #region 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出 foreach (DataColumn column in dtSource.Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(arrColName[column.Ordinal]); headerRow.GetCell(column.Ordinal).CellStyle = cHeadStyle; sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); } #endregion } #endregion } #endregion
#region 填充内容 IRow dataRow = sheet.CreateRow(rowIndex); if (dtSource.Columns.Contains("重复物料提示") && row["重复物料提示"].ToString() == "更新前数据") { rowStyle.FillPattern = FillPattern.SolidForeground; rowStyle.FillForegroundColor = GetXLColour(workbook, Color.Yellow); dataRow.RowStyle = rowStyle; isStyle = true; } foreach (DataColumn column in dtSource.Columns) {
ICell newCell = dataRow.CreateCell(column.Ordinal); newCell.CellStyle = isStyle?rowStyle: arryColumStyle[column.Ordinal]; string drValue = row[column].ToString(); SetCell(newCell, dateStyle, column.DataType, drValue); } #endregion rowIndex++; isStyle=false; } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; return ms; } } #endregion
#region ListExcel导出(加载模板) public static MemoryStream ExportListByTempale(List<TemplateDataModel> list, string templdateName) { try {
string templatePath = HttpContext.Current.Server.MapPath("/") + "/Resource/ExcelTemplate/"; string templdateName1 = string.Format("{0}{1}", templatePath, templdateName);
FileStream fileStream = new FileStream(templdateName1, FileMode.Open, FileAccess.Read); ISheet sheet = null; if (templdateName.IndexOf(".xlsx") == -1) { HSSFWorkbook hssfworkbook = new HSSFWorkbook(fileStream); sheet = hssfworkbook.GetSheetAt(0); SetPurchaseOrder(sheet, list); sheet.ForceFormulaRecalculation = true; using (MemoryStream ms = new MemoryStream()) { hssfworkbook.Write(ms); ms.Flush(); return ms; } } else { XSSFWorkbook xssfworkbook = new XSSFWorkbook(fileStream); sheet = xssfworkbook.GetSheetAt(0); SetPurchaseOrder(sheet, list); sheet.ForceFormulaRecalculation = true; using (MemoryStream ms = new MemoryStream()) { xssfworkbook.Write(ms); ms.Flush(); return ms; } }
} catch (Exception) { throw; } } private static void SetPurchaseOrder(ISheet sheet, List<TemplateDataModel> list) { try { foreach (var item in list) { IRow row = null; ICell cell = null; row = sheet.GetRow(item.row); if (row == null) { row = sheet.CreateRow(item.row); } cell = row.GetCell(item.cell); if (cell == null) { cell = row.CreateCell(item.cell); } cell.SetCellValue(item.value); } } catch (Exception) { throw; } } #endregion
#region 设置表格内容 private static void SetCell(ICell newCell, ICellStyle dateStyle, Type dataType, string drValue) { switch (dataType.ToString()) { case "System.String": newCell.SetCellValue(drValue); break; case "System.DateTime": System.DateTime dateV; if (System.DateTime.TryParse(drValue, out dateV)) { newCell.SetCellValue(dateV); } else { newCell.SetCellValue(""); } newCell.CellStyle = dateStyle; break; case "System.Boolean": bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "System.Int16": case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "System.Decimal": case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; case "System.DBNull": newCell.SetCellValue(""); break; default: newCell.SetCellValue(""); break; } } #endregion
#region 从Excel导入 public static DataTable ExcelImport(string strFileName) { DataTable dt = new DataTable();
ISheet sheet = null; using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) { if (strFileName.IndexOf(".xlsx") == -1) { HSSFWorkbook hssfworkbook = new HSSFWorkbook(file); sheet = hssfworkbook.GetSheetAt(0); } else { XSSFWorkbook xssfworkbook = new XSSFWorkbook(file); sheet = xssfworkbook.GetSheetAt(0); } }
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
IRow headerRow = sheet.GetRow(0); int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++) { ICell cell = headerRow.GetCell(j); dt.Columns.Add(cell.ToString()); }
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if(!row.IsEmpty()) { DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); }
dt.Rows.Add(dataRow); } } return dt; } public static DataTable ExcelImport(Stream fileStream, string flieType) { DataTable dt = new DataTable(); ISheet sheet = null; if (flieType == ".xls") { HSSFWorkbook hssfworkbook = new HSSFWorkbook(fileStream); sheet = hssfworkbook.GetSheetAt(0); } else { XSSFWorkbook xssfworkbook = new XSSFWorkbook(fileStream); sheet = xssfworkbook.GetSheetAt(0); } System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); IRow headerRow = sheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { ICell cell = headerRow.GetCell(j); dt.Columns.Add(cell.ToString()); } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); }
dt.Rows.Add(dataRow); } return dt; } #endregion
#region RGB颜色转NPOI颜色 private static short GetXLColour(HSSFWorkbook workbook, Color SystemColour) { short s = 0; HSSFPalette XlPalette = workbook.GetCustomPalette(); NPOI.HSSF.Util.HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B); if (XlColour == null) { if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255) { XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B); s = XlColour.Indexed; }
} else s = XlColour.Indexed; return s; } #endregion
#region 设置列的对齐方式 private static HorizontalAlignment getAlignment(string style) { switch (style) { case "center": return HorizontalAlignment.Center; case "left": return HorizontalAlignment.Left; case "right": return HorizontalAlignment.Right; case "fill": return HorizontalAlignment.Fill; case "justify": return HorizontalAlignment.Justify; case "centerselection": return HorizontalAlignment.CenterSelection; case "distributed": return HorizontalAlignment.Distributed; } return NPOI.SS.UserModel.HorizontalAlignment.General;
}
#endregion }
|