如何使用Apache poi更新现有的合并Excel单元格

时间:2013-05-13 05:56:53

标签: apache-poi

我无法更新这些合并和边框的现有Excel单元格。我创建了一个带有样式的Excel文件并用作模板。在我的代码 - >首先阅读Excel文件并更新我希望的单元格。没有合并单元格。但合并的单元格无法插入数据。

可能会产生损坏Excel文件或空数据单元格。我不想覆盖现有单元格的合并和边界。这是我的阅读和更新代码..

HashMap<String, ByteArrayOutputStream> streams = new HashMap<String, ByteArrayOutputStream>();
try {
    String appDir = System.getProperty("appDir");
    String resouceDir = appDir + System.getProperty("resourceDir");
    String templateDir = resouceDir + "/template";
    if (streams.keySet().size() <= 0) {
        XSSFSheet sheet = null;
        FileInputStream file = new FileInputStream(new File(templateDir +"/shipping_template.xlsx")); 
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        ByteArrayOutputStream baos = null;
        sheet = workbook.getSheetAt(0);
        XSSFRow shippingRow = sheet.getRow(4);
        Cell cell = shippingRow.createCell((short) 36);
        cell.setCellValue("DOOM Bringer");
        baos = new ByteArrayOutputStream();
        workbook.write(baos);
        streams.put(param, baos);
        baos.close();
        file.close();
    }
}

2 个答案:

答案 0 :(得分:1)

不幸的是,不再支持Apache POI。他们对办公室文档的完成方式进行了Office 2007更改的一个版本,不再支持此版本。我做了同样的事情,你可能想考虑使用docx4j。但无论您实际需要做什么,可能都会打开文件流一个新文档并将其保存到临时位置并对新文档进行更改,因为如果您尝试对其进行更改,可能会破坏原始文档。

答案 1 :(得分:0)

这个为我工作

CellRangeAddress region = sheet.getMergedRegion(index);   
int rowNum = region.getFirstRow(); // or region.getLastRow()
int colIndex = region.getFirstColumn(); // or region.getLastColumn()
Cell dateCell = sheet.getRow(rowNum).getCell(colIndex);
dateCell.setCellValue(today.toString("MM/dd/yyyy"));
相关问题