Java如何操作Excel并保存于原文档

大家对excel的操作可能更多的使用EasyExcel框架,但是我们需要了解一点。esayexcel库并不支持直接对原文件进行内容修改,它主要用于读取和写入Excel文件。如果要修改原文件的内容,我们需要使用到Java的POI库。

1,添加POI依赖

  <dependencies>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>5.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>5.0.0</version>
    </dependency>
  </dependencies>

2, 使用框架做具体处理

    public void testFile(File file, String page) {
        FileOutputStream fileOutputStream = null;
        try {
            // 读取Excel文件
            Integer rowNum = 0;
            Integer cellNum = 0;
            try (
                // 读取xlsx类型文件
                Workbook workbook = new XSSFWorkbook(Files.newInputStream(file.toPath()))) {
                // 选择处理的sheet
                Sheet sheet = workbook.getSheet(page);
                // 下面是我这边对某个数据列的处理
                for (int i = 0; i < 100; i++) {
                    for (int j = 0; j < 100; j++) {
                        Row row = sheet.getRow(j);
                        Cell cell = row.getCell(i);
                        // 定位到初始行和列
                        if (cell != null && cell.getCellType() == CellType.STRING && cell.getStringCellValue().equals("封签号")) {
                            rowNum = j;
                            cellNum = i;
                            break;
                        }
                    }
                }
                // 行不变,对列进行遍历处理
                for (int i = cellNum; i < 200; i++) {
                    Row row = sheet.getRow(rowNum);
                    Cell cell = row.getCell(cellNum);
                    if (cell.getCellType() == CellType.STRING) {
                        String newValue = re(cell.getStringCellValue()); // 用自定义方法处理数据
                        if (newValue == null) {
                            continue;
                        }
                        // 处理完后覆盖原值
                        cell.setCellValue(newValue);
                        rowNum++;
                    }
                }
                // 写回原文件
                fileOutputStream = new FileOutputStream(file.getAbsolutePath());
                workbook.write(fileOutputStream);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 注意关闭流
                IOUtils.closeQuietly(fileOutputStream);
            }
    }

3,如果需要打包成小工具进行使用还需增加

  <build>
    <!-- 项目最终打包成的名字 -->
    <finalName>community</finalName>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <classpathPrefix>lib/</classpathPrefix>
              <mainClass>com.rojer.MyApplication</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.10</version>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/lib</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>7</source>
          <target>7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

这样我们就能使用我们自己弄得小工具去处理一些常见的基本Excel操作了

打包完如图示:

接下里就可以直接点击进行运行处理了。

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java可以使用Apache POI库来解析Excel文件。以下是基本的步骤: 1. 添加POI库到项目中,可以通过Maven或手动下载和导入jar包的方式。具体可以参考官方文档:https://poi.apache.org/download.html 2. 通过输入流读取Excel文件,创建一个Workbook对象: ```java FileInputStream inputStream = new FileInputStream(new File("path/to/excel/file.xlsx")); Workbook workbook = new XSSFWorkbook(inputStream); // 或者 HSSFWorkbook(对应xls格式的文件) ``` 3. 获取要解析的Sheet: ```java Sheet sheet = workbook.getSheetAt(0); // 获取第一个Sheet ``` 4. 遍历Sheet中的每一行和每一列,读取单元格的数据: ```java // 遍历行 for (Row row : sheet) { // 遍历列 for (Cell cell : row) { switch (cell.getCellType()) { case STRING: System.out.print(cell.getStringCellValue() + "\t"); break; case NUMERIC: System.out.print(cell.getNumericCellValue() + "\t"); break; case BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t"); break; default: System.out.print("\t"); } } System.out.println(); } ``` 5. 关闭输入流和Workbook对象: ```java inputStream.close(); workbook.close(); ``` 完整的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelParser { public static void main(String[] args) throws IOException { FileInputStream inputStream = new FileInputStream(new File("path/to/excel/file.xlsx")); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { switch (cell.getCellType()) { case STRING: System.out.print(cell.getStringCellValue() + "\t"); break; case NUMERIC: System.out.print(cell.getNumericCellValue() + "\t"); break; case BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t"); break; default: System.out.print("\t"); } } System.out.println(); } inputStream.close(); workbook.close(); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值