Npoi 操作excel
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 628 629 630 631 632 633 634 635 636 637 638 639 640 | using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp { /// <summary> /// NPOIExcel 针对2.5.1.0出的NPOI操作Excel类的常用方法; /// </summary> public class NPOIHelper { /// <summary> /// 记录打开的Excel的路径 /// </summary> private string npoiFileName; /// <summary> /// 工作簿,全局变量 /// </summary> protected IWorkbook workbook; /// <summary> /// 获取工作表或是创建的 /// </summary> private NPOI.SS.UserModel.ISheet sheet; /// <summary> /// 构造方法 /// </summary> public NPOIHelper() { npoiFileName = "" ; workbook = new XSSFWorkbook(); } /// <summary> /// 打开 /// </summary> /// <param name="filename">excel文件路径</param> public void Open( string filename) { using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read)) { string ext = Path.GetExtension(filename).ToLower(); if (ext == ".xlsx" ) workbook = new XSSFWorkbook(fileStream); else { workbook = new HSSFWorkbook(fileStream); } } npoiFileName = filename; } /// <summary> /// 创建一个Excel对象,该对象为可见的 /// </summary> public void Create( string sheetname = "Sheet1" ) { sheet = workbook.CreateSheet(sheetname); } /// <summary> /// 获取一个工作表 /// </summary> /// <param name="SheetName">工作表名称</param> /// <returns></returns> public ISheet GetSheet( string SheetName) { return (sheet = workbook.GetSheet(SheetName) ?? workbook.CreateSheet(SheetName)); } /// <summary> /// 添加一个工作表 /// </summary> /// <param name="SheetName">工作表名称</param> /// <returns></returns> public ISheet AddSheet( string SheetName) { ISheet s = workbook.CreateSheet(SheetName); return s; } /// <summary> /// 删除一个工作表 /// </summary> /// <param name="SheetName">工作表名称</param> public void DelSheet( string SheetName) { int index = workbook.GetNameIndex(SheetName); workbook.RemoveSheetAt(index); } /// <summary> /// 重命名一个工作表 /// </summary> /// <param name="OldSheetName">老工作表名称</param> /// <param name="NewSheetName">新工作表名称</param> /// <returns></returns> public ISheet ReNameSheet( string OldSheetName, string NewSheetName) { int index = workbook.GetNameIndex(OldSheetName); workbook.SetSheetName(index, NewSheetName); return workbook.GetSheetAt(index); } /// <summary> /// 设置单元格的值 /// </summary> /// <param name="sheetName">工作表名称</param> /// <param name="row">行</param> /// <param name="col">列</param> /// <param name="value">设置的值</param> private void SetCellValue(ISheet sheetName, int row, int col, object value) { IRow _row = sheetName.GetRow(row) ?? sheetName.CreateRow(row); ICell cell = _row.GetCell(col) ?? _row.CreateCell(col); string valuetype = value.GetType().Name.ToLower(); switch (valuetype) { case "string" : //字符串类型 case "system.string" : case "datetime" : case "system.datetime" : //日期类型 case "boolean" : //布尔型 case "system.boolean" : //布尔型 cell.SetCellType(CellType.String); cell.SetCellValue(value.ToString()); break ; case "byte" : case "int" : case "int16" : case "int32" : case "int64" : case "system.int16" : //整型 case "system.int32" : case "system.int64" : case "system.byte" : cell.SetCellType(CellType.Numeric); cell.SetCellValue(Convert.ToInt32(value)); break ; case "single" : case "system.single" : case "double" : case "system.double" : case "decimal" : case "system.decimal" : cell.SetCellType(CellType.Numeric); cell.SetCellValue(Convert.ToDouble(value)); break ; case "dbnull" : //空值处理 case "system.dbnull" : //空值处理 cell.SetCellValue( "" ); break ; default : cell.SetCellValue(value.ToString()); break ; } } /// <summary> /// 要设值的工作表的名称 X行Y列 value 值 /// </summary> /// <param name="sheetName">工作表名</param> /// <param name="row">行</param> /// <param name="col">列</param> /// <param name="value">插入的值</param> public void SetCellValue( string sheetName, int row, int col, object value) { ISheet s = GetSheet(sheetName); SetCellValue(s, row, col, value); } /// <summary> /// 获取单元格值 /// </summary> /// <param name="sheetName">工作表名</param> /// <param name="row">行</param> /// <param name="col">列</param> /// <returns></returns> public ICell GetCell( string sheetName, int row, int col) { return GetSheet(sheetName).GetRow(row).Cells[col]; } /// <summary> /// 获取单元格值 /// </summary> /// <param name="sheetName">工作表名</param> /// <param name="row">行</param> /// <param name="col">列</param> /// <returns></returns> private ICell GetCell(ISheet sheetName, int row, int col) { //return ws.GetRow(row).Cells[col]; return sheetName.GetRow(row).GetCell(col); } /// <summary> /// 获取当前sheet的所有有数据的单元格 /// </summary> /// <param name="sheetName"></param> /// <returns></returns> public List<ICell> GetHasValueCell( string sheetName) { List<ICell> values = new List<ICell>(); var sheet = GetSheet(sheetName); int maxRow = sheet.LastRowNum + 1; int maxCol = MaxCellIndex(sheetName); for ( int row = 0; row < maxRow; row++) { for ( int col = 0; col < maxCol; col++) { try { //这一行查不到值的话会报错 ICell cell = sheet.GetRow(row)?.GetCell(col); if (cell != null ) values.Add(cell); } catch (Exception) { } } } return values; } /// <summary> /// 得到最大有效数据行索引 /// </summary> /// <param name="sheetName"></param> /// <returns></returns> public int MaxRowIndex( string sheetName) { var sheet = GetSheet(sheetName); return sheet.LastRowNum; } /// <summary> /// 得到最大有效数据列从1开始 /// </summary> /// <param name="sheetName"></param> /// <returns></returns> public int MaxCellIndex( string sheetName) { int maxCellIndex = -1; var sheet = GetSheet(sheetName); for ( int rowCnt = sheet.FirstRowNum; rowCnt <= sheet.LastRowNum; rowCnt++) //迭代所有行 { IRow row = sheet.GetRow(rowCnt); if (row != null && row.LastCellNum > maxCellIndex) { maxCellIndex = row.LastCellNum; } } return maxCellIndex; } /// <summary> /// 得到最大行和最大列的索引行从0开始列从0开始 /// </summary> /// <param name="sheetName"></param> /// <returns></returns> public ( int , int ) GetMaxRowIndexAndCellIndex( string sheetName) { return (MaxRowIndex(sheetName), MaxCellIndex(sheetName) - 1); } /// <summary> /// 得到最大行和最大列的索引,行从0开始列从1开始 /// </summary> /// <param name="sheetName"></param> /// <returns></returns> public ( int , int ) GetMaxRowIndexAndCell( string sheetName) { return (MaxRowIndex(sheetName), MaxCellIndex(sheetName)); } /// <summary> /// 清除某行的值和样式 /// </summary> /// <param name="sheetName"></param> /// <param name="rowIndex"></param> public void ClearRowValue( string sheetName, int rowIndex) { var sheet = GetSheet(sheetName); if (sheet == null ) return ; IRow row = sheet.GetRow(rowIndex); if (row == null ) return ; for ( int i = 0; i < row.LastCellNum; i++) { try { ICell cell = row.GetCell(i); cell.CellStyle = null ; cell.SetCellValue( string .Empty); } catch (Exception) { } } } /// <summary> /// 获取起止范围内的行列值 /// </summary> /// <param name="sheetName"></param> /// <param name="startRow"></param> /// <param name="startCol"></param> /// <param name="endRow"></param> /// <param name="endCol"></param> /// <returns></returns> public IList<ICell> GetCellsOfRange( string sheetName, int startRow, int startCol, int endRow, int endCol) { return (GetCellsOfRange(GetSheet(sheetName), startRow, startCol, endRow, endCol)); } /// <summary> /// 获取起止范围内的行列值 /// </summary> /// <param name="sheetName"></param> /// <param name="startRow"></param> /// <param name="startCol"></param> /// <param name="endRow"></param> /// <param name="endCol"></param> /// <returns></returns> private IList<ICell> GetCellsOfRange(ISheet sheetName, int startRow, int startCol, int endRow, int endCol) { IList<ICell> allCell = new List<ICell>(); for ( int i = startRow; i <= endRow; i++) for ( int j = startCol; j <= endCol; j++) { allCell.Add(GetCell(sheetName, i, j)); } return allCell; } /// <summary> /// 合并单元格 /// </summary> /// <param name="sheetName"></param> /// <param name="startRow"></param> /// <param name="endRow"></param> /// <param name="startCol"></param> /// <param name="endCol"></param> private void MergedCells(ISheet sheetName, int startRow, int endRow, int startCol, int endCol) { //CellRangeAddress四个参数为:起始行,结束行,起始列,结束列 var region = new CellRangeAddress(startRow, endRow, startCol, endCol); sheetName.AddMergedRegion(region); } /// <summary> /// 合并单元格 /// </summary> /// <param name="sheetName"></param> /// <param name="startRow"></param> /// <param name="startCol"></param> /// <param name="endRow"></param> /// <param name="endCol"></param> public void MergedCells( string sheetName, int startRow, int startCol, int endRow, int endCol) { MergedCells(GetSheet(sheetName), startRow, endRow, startCol, endCol); } /// <summary> /// 文档另存为 /// </summary> /// <param name="FileName"></param> /// <returns></returns> public bool SaveAs( string FileName) { npoiFileName = FileName; try { using (FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write)) { workbook.Write(fs); } return true ; } catch { return false ; } } /// <summary> /// 关闭 /// </summary> public void Close() { workbook.Close(); } /// <summary> /// 自适应宽度 /// </summary> /// <param name="sheetName">表名</param> /// <param name="startCol">起始列</param> /// <param name="endCol">结束列</param> public void AutoColumnWidth( string sheetName, int startCol, int endCol) { AutoColumnWidth(GetSheet(sheetName), startCol, endCol); } /// <summary> /// 自适应宽度 /// </summary> /// <param name="sheet"></param> /// <param name="cols"></param> private void AutoColumnWidth(ISheet sheet, int startCol, int endCol) { for ( int col = startCol; col <= endCol; col++) { sheet.AutoSizeColumn(col); //但是其实还是比实际文本要宽 } } /// <summary> /// 设置起止范围的行高,单位为磅 /// </summary> /// <param name="sheetName">工作表名称</param> /// <param name="startRow">起始行</param> /// <param name="endRow">结束行</param> /// <param name="heightValue">设置的高值</param> public void SetRowsHeight( string sheetName, int startRow, int endRow, int heightValue) { ISheet sheet = GetSheet(sheetName); for ( int i = startRow; i <= endRow; i++) { //sheet.GetRow(i).Height = Height * 20; sheet.GetRow(i).HeightInPoints = heightValue; } } /// <summary> /// 设置起止列的宽度,单位为字符 /// </summary> /// <param name="sheetName">工作表名称</param> /// <param name="startCol">起始列</param> /// <param name="endCol">结束列</param> /// <param name="widthValue">设置的宽度值</param> public void SetColumnsWidth( string sheetName, int startCol, int endCol, int widthValue) { ISheet sheet = GetSheet(sheetName); for ( int j = startCol; j <= endCol; j++) { sheet.SetColumnWidth(j, widthValue * 256); } } /// <summary> /// 插入新行 /// </summary> /// <param name="sheetName">工作表名</param> /// <param name="insertRowIndex">插入的行索引位置</param> /// <param name="insertRowCount">插入的行数量</param> /// <param name="formatRowIndex">获取插入行的参照样式的行索引</param> public void InsertRow( string sheetName, int insertRowIndex, int insertRowCount, int formatRowIndex) { ISheet sheet = GetSheet(sheetName); IRow formatRow = sheet.GetRow(formatRowIndex); InsertRow(sheet, insertRowIndex, insertRowCount, formatRow); } /// <summary> /// 插入新行 /// </summary> /// <param name="sheetName"></param> /// <param name="insertRowIndex"></param> /// <param name="insertRowCount"></param> /// <param name="formatRow"></param> private void InsertRow(ISheet sheetName, int insertRowIndex, int insertRowCount, IRow formatRow) { sheet.ShiftRows(insertRowIndex, sheet.LastRowNum, insertRowCount, true , false ); for ( int i = insertRowIndex; i < insertRowIndex + insertRowCount; i++) { IRow targetRow = null ; ICell sourceCell = null ; ICell targetCell = null ; targetRow = sheet.CreateRow(i); for ( int m = formatRow.FirstCellNum; m < formatRow.LastCellNum; m++) { sourceCell = formatRow.GetCell(m); if (sourceCell == null ) { continue ; } targetCell = targetRow.CreateCell(m); targetCell.CellStyle = sourceCell.CellStyle; targetCell.SetCellType(sourceCell.CellType); } } for ( int i = insertRowIndex; i < insertRowIndex + insertRowCount; i++) { IRow firstTargetRow = sheet.GetRow(i); ICell firstSourceCell = null ; ICell firstTargetCell = null ; for ( int m = formatRow.FirstCellNum; m < formatRow.LastCellNum; m++) { firstSourceCell = formatRow.GetCell(m, MissingCellPolicy.CREATE_NULL_AS_BLANK); if (firstSourceCell == null ) { continue ; } firstTargetCell = firstTargetRow.GetCell(m, MissingCellPolicy.CREATE_NULL_AS_BLANK); firstTargetCell.CellStyle = firstSourceCell.CellStyle; firstTargetCell.SetCellType(firstSourceCell.CellType); } } } //--------------------------------------------------------------------新增的方法------------------------------------- #region 自定义样式 /// <summary> /// 自定义样式 /// </summary> /// <param name="fontSize"></param> /// <param name="fontName"></param> /// <param name="horizontalAlignment"></param> /// <param name="verticalAlignment"></param> /// <returns></returns> public ICellStyle CreateCellStyle( int fontSize, string fontName, bool fontBold, HorizontalAlignment horizontal, VerticalAlignment vertical, BorderStyle borderStyle) { ICellStyle style = workbook.CreateCellStyle(); IFont font = workbook.CreateFont(); font.FontName = fontName; font.FontHeightInPoints = ( short )fontSize; if (fontBold) font.Boldweight = ( short )FontBoldWeight.Bold; //字体加粗 style.Alignment = horizontal; style.VerticalAlignment = vertical; style.SetFont(font); style.BorderLeft = borderStyle; style.BorderRight = borderStyle; style.BorderTop = borderStyle; style.BorderBottom = borderStyle; return style; } /// <summary> /// 得到数据行常规样式(11 字号+居中对齐) /// </summary> /// <returns></returns> public ICellStyle GetNormalCellStyle() { return GetNormalCellStyle(11, HorizontalAlignment.Center); } public ICellStyle GetNormalCellStyle( int fontSize, HorizontalAlignment horizontal) { return CreateCellStyle(fontSize, "Arial" , false , horizontal, VerticalAlignment.Center, BorderStyle.Thin); } /// <summary> /// 得到标题样式(20字号+加粗+居中对齐) /// </summary> /// <returns></returns> public ICellStyle GetHeaderCellStyle() { return CreateCellStyle(20, "Arial" , true , HorizontalAlignment.Center, VerticalAlignment.Center, BorderStyle.Thin); } #endregion #region 设置行列的边框,以及样式 /// <summary> /// 设置指定列,指定范围行的边框 (传从0 开始的索引) /// </summary> public void SetCellRangeBorder( string sheetName, int cellIndex, int startRow, int endRow, ICellStyle cellStyle) { SetRengeBorder(sheetName, startRow, cellIndex, endRow, cellIndex, cellStyle); } /// <summary> /// 设置指定行指定范围列的边框(传从0 开始的索引) /// </summary> public void SetRowRangeBorder( string sheetName, int rowIndex, int startCell, int endCell, ICellStyle cellStyle) { SetRengeBorder(sheetName, rowIndex, startCell, rowIndex, endCell, cellStyle); } /// <summary> /// 设置指定范围的边框,(传从0 开始的索引) /// </summary> public void SetRengeBorder( string sheetName, int startRow, int startCell, int endRow, int endCell, ICellStyle cellStyle) { var sheet = GetSheet(sheetName); for ( int i = startRow; i <= endRow; i++) { for ( int n = startCell; n <= endCell; n++) { var row = sheet.GetRow(i) ?? sheet.CreateRow(i); var cell = row.GetCell(n); if (cell == null ) { cell = sheet.GetRow(i).CreateCell(n); } cell.CellStyle = cellStyle; } } } #endregion #region 合并单元格,带样式 /// <summary> /// 合并单元格常规样式 /// </summary> /// <param name="sheetName"></param> /// <param name="startRow"></param> /// <param name="startCol"></param> /// <param name="endRow"></param> /// <param name="endCol"></param> public void MergedCellsStyle( string sheetName, int startRow, int startCol, int endRow, int endCol) { MergedCellsStyle(sheetName, startRow, startCol, endRow, endCol, GetNormalCellStyle()); } /// <summary> /// 合并单元格指定样式 /// </summary> /// <param name="sheetName"></param> /// <param name="startRow"></param> /// <param name="startCol"></param> /// <param name="endRow"></param> /// <param name="endCol"></param> /// <param name="cellStyle"></param> public void MergedCellsStyle( string sheetName, int startRow, int startCol, int endRow, int endCol, ICellStyle cellStyle) { MergedCells(GetSheet(sheetName), startRow, endRow, startCol, endCol); for ( int i = startRow; i <= endRow; i++) { SetRowRangeBorder(sheetName, i, startCol, endCol, cellStyle); } } #endregion /// <summary> /// 设置表格内有效数据行样式(全部行)(填充完数据后调用) /// </summary> /// <param name="sheetName"></param> /// <param name="cellStyle">样式</param> /// <param name="isIgnoreHeader">是否忽略掉标题,前两行</param> /// <param name="isAutoW">内容是否自适应宽度</param> public void SetValidDataRowStyle( string sheetName, ICellStyle cellStyle, bool isIgnoreHeader = true , bool isAutoW = true ) { var (row, cell) = GetMaxRowIndexAndCellIndex(sheetName); int startRow = isIgnoreHeader ? 2 : 0; SetRengeBorder(sheetName, startRow, 0, row, cell, cellStyle); if (isAutoW) AutoColumnWidth(sheetName, 0, cell); } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现