【开发指南】Spring Cloud集成POI完成Excel读写操作
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class ExcelUtil {
public static Workbook readExcel(String filePath) throws IOException {
InputStream is = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(is);
return workbook;
}
public static void writeExcel(Workbook workbook, String filePath) throws IOException {
FileOutputStream fos = new FileOutputStream(filePath);
workbook.write(fos);
fos.close();
}
public static void main(String[] args) {
try {
Workbook workbook = readExcel("example.xlsx");
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
if (row == null) {
row = sheet.createRow(0);
}
Cell cell = row.getCell(0);
if (cell == null) {
cell = row.createCell(0);
}
cell.setCellValue("新值");
writeExcel(workbook, "example_modified.xlsx");
} catch (IOException e) {
e.printStackTrace();
}
}
}
这段代码展示了如何使用Apache POI库来读取和写入Excel文件。readExcel
方法用于打开一个Excel文件并返回一个Workbook
对象。writeExcel
方法用于将Workbook
对象写入到一个文件中。在main
方法中,我们读取了一个名为example.xlsx
的Excel文件,修改了第一行第一列的值,并将修改后的Workbook
写入到了一个新的文件example_modified.xlsx
中。
评论已关闭