向excel中追加內(nèi)容

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文件中寫數(shù)據(jù)
            FileOutputStream out = new FileOutputStream(filePath);
            // 獲取到最后一行
            int physicalNumberOfRows = sheetAt.getPhysicalNumberOfRows();
            for (int i = 0; i < physicalNumberOfRows; i++) {
                // 獲取第i行(excel中的行默認(rèn)從0開始,所以這就是為什么,一個(gè)excel必須有字段列頭),即,字段列頭,便于賦值
                XSSFRow row = sheetAt.getRow(i);
                //獲取第一列數(shù)據(jù)
                String content1= getCellValue(row.getCell(1));
                row.createCell(21).setCellValue(content1+1); // 設(shè)置第二個(gè)(從0開始)單元格的數(shù)據(jù)
                row.createCell(22).setCellValue(content1+2); // 設(shè)置第二個(gè)(從0開始)單元格的數(shù)據(jù)
            }
            out.flush();
            hssfWorkbook.write(out);
            out.close();
            return new JsonResult(true, "excel success!");
        } catch (Exception e) {
            log.error("向excel中寫入數(shù)據(jù)時(shí)發(fā)生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();
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容