美文网首页工具类
向excel中追加内容

向excel中追加内容

作者: 星钻首席小管家 | 来源:发表于2022-07-08 13:43 被阅读0次

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();
    }

相关文章

网友评论

    本文标题:向excel中追加内容

    本文链接:https://www.haomeiwen.com/subject/vncvbrtx.html