C#用NPOI复制当前表生成一个新表
时间: 2024-03-22 15:41:15 浏览: 56
C#Winform使用NPOI生成excel文件
可以使用NPOI来复制当前表并生成一个新表,具体步骤如下:
1. 获取当前工作表
```
ISheet sourceSheet = workbook.GetSheetAt(0);
```
2. 创建新表格并将原始表格的名称复制到新表格中
```
ISheet newSheet = workbook.CreateSheet("NewSheet");
```
3. 复制原始表格中的行到新表格中
```
for (int i = 0; i <= sourceSheet.LastRowNum; i++)
{
IRow sourceRow = sourceSheet.GetRow(i);
IRow newRow = newSheet.CreateRow(i);
if (sourceRow != null)
{
for (int j = 0; j < sourceRow.LastCellNum; j++)
{
ICell sourceCell = sourceRow.GetCell(j);
ICell newCell = newRow.CreateCell(j);
if (sourceCell != null)
{
newCell.SetCellValue(sourceCell.ToString());
}
}
}
}
```
完整代码如下:
```
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
public void CopyCurrentSheet(string sourcePath, string destinationPath)
{
// 打开源工作簿
using (FileStream sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
{
XSSFWorkbook sourceWorkbook = new XSSFWorkbook(sourceStream);
// 获取当前工作表
ISheet sourceSheet = sourceWorkbook.GetSheetAt(0);
// 创建新工作簿
IWorkbook workbook = new XSSFWorkbook();
// 创建新表格并将名称复制到新表格中
ISheet newSheet = workbook.CreateSheet("NewSheet");
// 复制每行
for (int i = 0; i <= sourceSheet.LastRowNum; i++)
{
IRow sourceRow = sourceSheet.GetRow(i);
IRow newRow = newSheet.CreateRow(i);
if (sourceRow != null)
{
// 复制每个单元格
for (int j = 0; j < sourceRow.LastCellNum; j++)
{
ICell sourceCell = sourceRow.GetCell(j);
ICell newCell = newRow.CreateCell(j);
if (sourceCell != null)
{
newCell.SetCellValue(sourceCell.ToString());
}
}
}
}
// 保存新工作簿
using (FileStream destinationStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write))
{
workbook.Write(destinationStream);
}
}
}
```
阅读全文