Java读取Excel模板并写入内容(保留原有样式)

此方法使用与单个或多个Sheet
代码中两个for循环是由于我的Excel是动态的
所以根据自己Excel的需求
主要代码在于

Row row = sheet.getRow(j + 5);
row.createCell(17);
Cell cell = row.getCell(17);
cell.setCellType(CellType.STRING);
cell.setCellValue(arInfo.get(j).getResultMsg());

当时在使用时,没有加row.createCell(17),结果报错空异常,因此建议根据自己的情况自己的row.getcell是否为空。

/**
	 * 寫入Excel模板 (會保留原本的樣式)
	 * @param filename
	 * @param sheetCount
	 */
	public void writeExcelFile(File file, String filename, List listSheet) {
        Workbook workbook = null;
        try {
        	BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));
        	workbook = WorkbookFactory.create(is); 
        } catch (Exception e) {
        }
        for (int i = 0; i < listSheet.size(); i++) {
			SheetInfo sheetInfo = listSheet.get(i);
			List arInfo = sheetInfo.getListAR();
			List apInfo = sheetInfo.getListAP();
			 //查找到指定的sheet
	        Sheet sheet = workbook.getSheetAt(i);
	        sheet.setForceFormulaRecalculation(true);
	        for (int j = 0; j < arInfo.size(); j++) {
	        	 Row row = sheet.getRow(j + 5);
	        	 row.createCell(17);
	        	 Cell cell = row.getCell(17);
	        	 cell.setCellType(CellType.STRING);
	             cell.setCellValue(arInfo.get(j).getResultMsg());
			}
	        for (int j = 0; j < apInfo.size(); j++) {
	        	Row row = sheet.getRow((j + 4 + arInfo.size() + 4));
	        	 row.createCell(17);
	        	 Cell cell = row.getCell(17);
	        	 cell.setCellType(CellType.STRING);
	             cell.setCellValue(apInfo.get(j).getResultMsg());
			}
		}
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            workbook.write(bos);
            File outfile = new File(filename);
            FileOutputStream fileOutputStream = new FileOutputStream(outfile);
            fileOutputStream.write(bos.toByteArray());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

你可能感兴趣的:(poi,excel)