使用 NPOI 库轻松合并 Excel 文件中的重复行。此教程提供了详细的步骤和代码示例,演示如何使用 NPOI 库来处理 Excel 文件并删除重复的行。

  1. 导入 NPOI 库的命名空间:
using NPOI.HSSF.UserModel; // HSSF 用于处理 xls 格式的 Excel 文件
using NPOI.SS.UserModel; // SS 用于处理 xlsx 格式的 Excel 文件
using NPOI.XSSF.UserModel; // XSSF 用于处理 xlsx 格式的 Excel 文件
  1. 打开 Excel 文件并创建工作簿和工作表对象:
string filePath = "your_file_path";
IWorkbook workbook;
ISheet sheet;
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
    if (filePath.EndsWith(".xls"))
        workbook = new HSSFWorkbook(file); // 处理 xls 格式的 Excel 文件
    else if (filePath.EndsWith(".xlsx"))
        workbook = new XSSFWorkbook(file); // 处理 xlsx 格式的 Excel 文件
    else
        throw new Exception("Invalid Excel file format");
    sheet = workbook.GetSheetAt(0); // 获取第一个工作表
}
  1. 遍历工作表的行并判断是否有重复行,如果有,则合并重复行:
for (int rowIndex = sheet.FirstRowNum + 1; rowIndex <= sheet.LastRowNum; rowIndex++)
{
    IRow currentRow = sheet.GetRow(rowIndex);
    IRow previousRow = sheet.GetRow(rowIndex - 1);
    bool isDuplicateRow = true;

    for (int cellIndex = 0; cellIndex < currentRow.LastCellNum; cellIndex++)
    {
        ICell currentCell = currentRow.GetCell(cellIndex);
        ICell previousCell = previousRow.GetCell(cellIndex);

        if (currentCell != null && previousCell != null)
        {
            if (!currentCell.ToString().Equals(previousCell.ToString()))
            {
                isDuplicateRow = false;
                break;
            }
        }
        else if (currentCell != null || previousCell != null)
        {
            isDuplicateRow = false;
            break;
        }
    }

    if (isDuplicateRow)
    {
        sheet.RemoveRow(currentRow);
    }
}
  1. 保存修改后的 Excel 文件:
using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
    workbook.Write(file);
}

请注意,这只是一个简单的示例,只能处理单个工作表的重复行合并。如果要处理多个工作表或更复杂的合并需求,可能需要进行更多的代码编写和调整。


原文地址: https://www.cveoy.top/t/topic/p6IB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录