Excel文件按部门切分成多个文件

一、需求

1、文件夹按部门创建

2、文件名按原始文件名命名

二、代码实现

java 复制代码
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author xhm
 * @Date 2025 01 17 09 50
 **/

public class ExcelDataProcessing {
  public static void main(String[] args) {
    String inputFilePath = "管理版_投入部门工时汇总.xls";  // 输入的 Excel 文件路径
    String outputDirectory = "部门";  // 输出目录

    if (args.length >= 1) {
      inputFilePath = args[0];
    }
    if (args.length >= 2) {
      outputDirectory = args[1];
    }

    try (FileInputStream inputStream = new FileInputStream(new File(inputFilePath));
         Workbook inputWorkbook = new XSSFWorkbook(inputStream)) {

      Sheet inputSheet = inputWorkbook.getSheetAt(0);  // 获取第一个工作表
      String inputSheetName = inputSheet.getSheetName();  // 获取输入工作表的名称
      String inputFileName = new File(inputFilePath).getName();  // 获取输入 Excel 的文件名
      Map<String, Workbook> departmentWorkbooks = new HashMap<>();  // 存储不同部门的工作簿

      // 遍历每一行,假设第一行是标题行,从第二行开始处理数据
      for (int i = 1; i <= inputSheet.getLastRowNum(); i++) {
        Row row = inputSheet.getRow(i);
        if (row == null) continue;

        // 假设部门信息在第一列
        Cell departmentCell = row.getCell(2);
        if (departmentCell == null) continue;

        String department = departmentCell.getStringCellValue();
        // 如果该部门的工作簿还未创建,则创建一个新的工作簿
        if (!departmentWorkbooks.containsKey(department)) {
          Workbook departmentWorkbook = new XSSFWorkbook();
          Sheet departmentSheet = departmentWorkbook.createSheet(inputSheetName);  // 使用输入工作表的名称创建新工作表
          // 复制标题行
          Row titleRow = inputSheet.getRow(0);
          Row newTitleRow = departmentSheet.createRow(0);
          copyRow(titleRow, newTitleRow);
          departmentWorkbooks.put(department, departmentWorkbook);
        }

        // 获取该部门的工作簿和工作表
        Workbook departmentWorkbook = departmentWorkbooks.get(department);
        Sheet departmentSheet = departmentWorkbook.getSheet(inputSheetName);
        int lastRowNum = departmentSheet.getLastRowNum();
        Row newRow = departmentSheet.createRow(lastRowNum + 1);
        // 复制数据行
        copyRow(row, newRow);
      }

      // 保存每个部门的工作簿到以部门命名的文件夹中
      for (Map.Entry<String, Workbook> entry : departmentWorkbooks.entrySet()) {
        String department = entry.getKey();
        Workbook departmentWorkbook = entry.getValue();
        File departmentFolder = new File(outputDirectory, department);
        if (!departmentFolder.exists()) {
          departmentFolder.mkdirs();  // 创建部门文件夹
        }
        String outputFilePath = departmentFolder.getAbsolutePath() + File.separator + inputFileName;  // 保留输入 Excel 的文件名
        try (FileOutputStream outputStream = new FileOutputStream(outputFilePath)) {
          departmentWorkbook.write(outputStream);
        }
      }
    } catch (IOException e) {
      System.err.println("Error processing Excel file: " + e.getMessage());
    }
  }

  private static void copyRow(Row sourceRow, Row destinationRow) {
    for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
      System.out.println("代码执行中");
      Cell sourceCell = sourceRow.getCell(i);
      Cell destinationCell = destinationRow.createCell(i);
      if (sourceCell == null) continue;

      // 复制单元格样式
      CellStyle newCellStyle = destinationRow.getSheet().getWorkbook().createCellStyle();
      newCellStyle.cloneStyleFrom(sourceCell.getCellStyle());
      destinationCell.setCellStyle(newCellStyle);

      // 复制单元格内容
      switch (sourceCell.getCellType()) {
        case STRING:
          destinationCell.setCellValue(sourceCell.getStringCellValue());
          break;
        case NUMERIC:
          if (DateUtil.isCellDateFormatted(sourceCell)) {
            destinationCell.setCellValue(sourceCell.getDateCellValue());
          } else {
            destinationCell.setCellValue(sourceCell.getNumericCellValue());
          }
          break;
        case BOOLEAN:
          destinationCell.setCellValue(sourceCell.getBooleanCellValue());
          break;
        default:
          destinationCell.setCellValue("");
      }
    }
  }
}

三、依赖引用

XML 复制代码
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
相关推荐
課代表35 分钟前
Excel VBA 为数据赋予随机浅色标记
excel·vba·可视化·条件格式·标记·对比·随机
kylezhao20195 小时前
C#上位机开发数据持久化:excel报表导入导出
开发语言·c#·excel
悟能不能悟5 小时前
springboot controller返回的是HttpServletResponse成功返回excel文件流,失败就返回失败参数
spring boot·后端·excel
野比带雄1 天前
対excel时间格式的理解
excel
缺点内向1 天前
Java:轻松实现 Excel 文档属性添加
java·开发语言·excel
Teable任意门互动1 天前
从飞书多维表格 简道云到Teable多维表格:企业为何选择Teable作为新一代智能数据协作平台?
数据库·excel·钉钉·飞书·开源软件
AC赳赳老秦1 天前
DeepSeek + Excel 实战:多表联动分析与异常数据自动预警教程
microsoft·rabbitmq·excel·etcd·memcached·memcache·deepseek
2501_930707781 天前
如何使用C#代码将 Excel 文件转换为 SVG
开发语言·c#·excel
Eiceblue2 天前
将 Python 列表导出为 Excel 文件:一维、二维、字典列表
开发语言·python·excel·visual studio code
Shi_haoliu2 天前
inno setup6.6.1实例,制作安装包,创建共享文件夹,写入注册表(提供给excel加载项,此文章解释iss文件)
前端·vue.js·windows·excel