poi依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
public static void main(String[] args) {
File file = new File("文件路径");
Workbook workbook = readExcel(file);
handleData(workbook);
try {
FileOutputStream stream = FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
示例1
public static void handleData(Workbook workbook){
Sheet sheet = workbook.getSheetAt(0);
Row titleRow = sheet.getRow(0);
short lastCellNum = titleRow.getLastCellNum();
int titleNum = -1;
for (int i = 0; i < lastCellNum; i++) {
if (titleRow.getCell(i).getStringCellValue().equals("征用")) {
titleNum = i;
break;
}
}
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
if (row != null) {
if (row.getLastCellNum() < 1 || "".equals(row.getCell(0))) {
continue;
}
}
Cell cell = row.getCell(titleNum);
if (cell == null) {
row.createCell(titleNum).setCellValue("呀呀呀");
} else if ("".equals(cell.getStringCellValue())) {
cell.setCellValue("呀呀呀呀呀");
}
}
}
获取工作簿
public static Workbook readExcel(File file) {
Workbook xssfWorkbook = null;
try {
//获取文件名字
String fileName = file.getName();
//获取文件类型
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
//获取输入流
InputStream stream = new FileInputStream(file);
//获取工作薄
xssfWorkbook = null;
if (fileType.equals("xls")) {
xssfWorkbook = new HSSFWorkbook(stream);
} else if (fileType.equals("xlsx")) {
xssfWorkbook = new XSSFWorkbook(stream);
} else {
System.out.println("excel格式不正确");
}
} catch (IOException e) {
e.printStackTrace();
}
return xssfWorkbook;
}
```java
</details>