C#使用NPOI的方式操作Excel复制行

您所在的位置:网站首页 excel复制模板 C#使用NPOI的方式操作Excel复制行

C#使用NPOI的方式操作Excel复制行

2023-08-05 04:27| 来源: 网络整理| 查看: 265

The interface is prepared for NPOI 2.0 actually. In NPOI 2.0, there are two namespace: XSSF and HSSF. XSSF is for xlsx, HSSF is for xls. Both implements interfaces in NPOI.SS; NPOI有3种dll:①XSSF操作xlsx格式版本的Excel;②HSSF操作xls格式版本的Excel;③SS以上两种格式的Excel都可操作; 下面的方式是使用SS的类下方法写的;

/// Description: Inserts a existing row into a new row, will automatically push down /// any existing rows. Copy is done cell by cell and supports, and the /// command tries to copy all properties available (style, merged cells, values, etc...) /// private void CopyRow(IWorkbook workbook, ISheet worksheet, int sourceRowNum, int destinationRowNum) { // Get the source / new row IRow newRow = worksheet.GetRow(destinationRowNum); IRow sourceRow = worksheet.GetRow(sourceRowNum); // If the row exist in destination, push down all rows by 1 else create a new row if (newRow != null) { worksheet.ShiftRows(destinationRowNum, worksheet.LastRowNum, 1); } else { newRow = worksheet.CreateRow(destinationRowNum); } // Loop through source columns to add to new row for (int i = 0; i newCell = null; continue; } // Copy style from old cell and apply to new cell ICellStyle newCellStyle = workbook.CreateCellStyle(); newCellStyle.CloneStyleFrom(oldCell.CellStyle); ; newCell.CellStyle = newCellStyle; // If there is a cell comment, copy if (newCell.CellComment != null) newCell.CellComment = oldCell.CellComment; // If there is a cell hyperlink, copy if (oldCell.Hyperlink != null) newCell.Hyperlink = oldCell.Hyperlink; // Set the cell data type newCell.SetCellType(oldCell.CellType); // Set the cell data value switch (oldCell.CellType) { case CellType.Blank: newCell.SetCellValue(oldCell.StringCellValue); break; case CellType.Boolean: newCell.SetCellValue(oldCell.BooleanCellValue); break; case CellType.Error: newCell.SetCellErrorValue(oldCell.ErrorCellValue); break; case CellType.Formula: newCell.SetCellFormula(oldCell.CellFormula); break; case CellType.Numeric: newCell.SetCellValue(oldCell.NumericCellValue); break; case CellType.String: newCell.SetCellValue(oldCell.RichStringCellValue); break; case CellType.Unknown: newCell.SetCellValue(oldCell.StringCellValue); break; } } // If there are are any merged regions in the source row, copy to new row for (int i = 0; i CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.RowNum, (newRow.RowNum + (cellRangeAddress.FirstRow - cellRangeAddress.LastRow)), cellRangeAddress.FirstColumn, cellRangeAddress.LastColumn); worksheet.AddMergedRegion(newCellRangeAddress); } } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3