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操作了
打包完如图示:

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