目录
POI实现读写Excel
旧版本-以xlsx结尾
引入依赖
<!--旧版本,以xls结尾-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
controller层
@Autowired ExcelUtilService excelUtilService;
@PostMapping("/write/old")
public void writeExcelFile_old(){
excelUtilService.writeExcelFile_old();
}
@GetMapping("/read/old")
public List<ExcelDemo> readExcelFile_old() throws IOException {
List<ExcelDemo> excelDemos = excelUtilService.readExcelFile_old();
return excelDemos;
}
service层
String path = "D:\\target\\";
//写入
public void writeExcelFile_old() {
//创建一个工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个工作表
HSSFSheet sheet = workbook.createSheet("旧版测试");
//锁定一个单元格
Row row_1 = sheet.createRow(0);//先锁定第一行
Cell cell_11 = row_1.createCell(0);//再锁定一列,就能锁定一个单元格
cell_11.setCellValue("id");//在单元格里填东西
row_1.createCell(1).setCellValue("姓名");
//后面就是重复前面的操作
Row row_2 = sheet.createRow(1);
row_2.createCell(0).setCellValue(1);
row_2.createCell(1).setCellValue("LUCY");
//使用文件输出流来写数据
try {
//创建文件
File filepath = new File(path);
//判断路径文件夹是否存在
if(!filepath.exists()){
//boolean flag=file.mkdir();//只创建最后一个文件夹。父文件夹必须存在才能创建成功。
boolean flag=filepath.mkdirs();//无论父文件夹是否存在,都会创建。
}
FileOutputStream fileOutputStream = new FileOutputStream(new File(path + "旧版测试.xls"));
workbook.write(fileOutputStream);
//关闭流
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOExc