【问题标题】:How can I change TextBox in Excel with XSSF from Apache POI如何使用 Apache POI 中的 XSSF 更改 Excel 中的 TextBox
【发布时间】:2014-06-27 09:26:28
【问题描述】:

我正在使用 Apache POI 来处理 Excel 文件。我的 Excel 文件有 2 个文本框,我想为其读取文本并进行更改。 XSSF 模型怎么可能?我不想创建一个新的文本框——我知道怎么做。到目前为止,我一直在尝试,但那里没有 TextBox(我可以看到)。

XSSFWorkbook wb = //get the Workbook somehow
        XSSFSheet sheet = wb.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.rowIterator();
        while(rowIterator.hasNext()){
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while(cellIterator.hasNext()){
                Cell cell = cellIterator.next();
            }
        }
        for(PackagePart pp : wb.getAllEmbedds()){

        }

那么文本框在哪里?

【问题讨论】:

    标签: java excel apache-poi xssf


    【解决方案1】:

    这是我在 POI 3.10 中获取对文本框的引用并更改其内容的操作。

    对于 XSSF(未经测试):

    XSSFDrawing draw = sheet.createDrawingPatriarch();
    List<XSSFShape> shapes = draw.getShapes();
    Iterator<XSSFShape> it = shapes.iterator();
    
    while(it.hasNext()) {           
        XSSFShape shape = it.next();
        if (shape instanceof XSSFTextBox){
            XSSFTextBox textbox = (XSSFTextBox) shape;
            textbox.setText("foo"); // Could take an XSSFRichTextString instead
        }
    } 
    

    对于 HSSF:

    HSSFPatriarch pat = (HSSFPatriarch) sheet.createDrawingPatriarch();
    List<HSSFShape> children = pat.getChildren();
    Iterator<HSSFShape> it = children.iterator();
    HSSFRichTextString richStr = new HSSFRichTextString("foo"); 
    
    while(it.hasNext()) {           
        HSSFShape shape = it.next();
        if (shape instanceof HSSFTextbox){
            HSSFTextbox textbox = (HSSFTextbox) shape;
            textbox.setString(richStr);
        }
    }
    

    这个解决方案似乎不是很灵活,因为为不同的文本框设置不同的值需要一些条件逻辑。对我来说幸运的是,我只是将所有文本框更改为相同的文本。

    改编自:Obtain textbox value from Excel in Java

    【讨论】:

    • 我正在使用 XSSF 而不是 HSSF。知道如何为 XSSF 做这件事吗?
    • 哦,对不起,我没有。我用我认为可行的方法更新了我的答案(使用与我的 HSSF 方法相同的基本解决方案)。参考这个:poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/…
    • 对于 XSSF,您可以将 XSSFTextbox 更改为 XSSFSimpleShape
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多