向excel中追加内容

1.加入poi的依赖
2.demo

public JsonResult test(String filePath){
        try {
            filePath = "C:\\Users\\Administrator\\Desktop\\1.xlsx";
            FileInputStream fs = new FileInputStream(filePath);
            XSSFWorkbook hssfWorkbook =new XSSFWorkbook(fs);
            XSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);
            // 向xls文件中写数据
            FileOutputStream out = new FileOutputStream(filePath);
            // 获取到最后一行
            int physicalNumberOfRows = sheetAt.getPhysicalNumberOfRows();
            for (int i = 0; i < physicalNumberOfRows; i++) {
                // 获取第i行(excel中的行默认从0开始,所以这就是为什么,一个excel必须有字段列头),即,字段列头,便于赋值
                XSSFRow row = sheetAt.getRow(i);
                //获取第一列数据
                String content1= getCellValue(row.getCell(1));
                row.createCell(21).setCellValue(content1+1); // 设置第二个(从0开始)单元格的数据
                row.createCell(22).setCellValue(content1+2); // 设置第二个(从0开始)单元格的数据
            }
            out.flush();
            hssfWorkbook.write(out);
            out.close();
            return new JsonResult(true, "excel success!");
        } catch (Exception e) {
            log.error("向excel中写入数据时发生IO异常,异常如下:{}",e);
            return new JsonResult(false, "excel fail message:"+e.getMessage());
        }
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) return null;
        cell.setCellType(CellType.STRING);
        return cell.getStringCellValue();
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容