Apache POI:从文本框中获取价值

时间:2016-03-15 15:29:39

标签: java apache-poi

我目前正在编写从excel文件中读取值的程序。 对于普通的单元格,它工作正常,但也有文本框,选择框和组合框,我无法真正访问。我知道,这些元素是用id创建的。

这是我目前的尝试:

private void processExcelToXml(File excelFile) throws EncryptedDocumentException, IOException {
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(excelFile));
    List<HSSFObjectData> embeddedObjects = workbook.getAllEmbeddedObjects();
    List<HSSFObjectData> textBoxList = new ArrayList<>();
    List<HSSFObjectData> comboBoxList = new ArrayList<>();
    List<HSSFObjectData> checkBoxList = new ArrayList<>();


    for (HSSFObjectData hssfObjectData : embeddedObjects) {
        log.info(hssfObjectData.getDirectory().getName());
        switch (hssfObjectData.getOLE2ClassName()) {

            case "Forms.TextBox.1":
                textBoxList.add(hssfObjectData);
                break;
            case "Forms.CheckBox.1":
                checkBoxList.add(hssfObjectData);
                break;
            case "Forms.ComboBox.1":
                comboBoxList.add(hssfObjectData);
                break;
            default:
                break;
        }
    }
}

我知道有一个解决方案(Obtain textbox value from Excel in Java),但是和OP一样,我没有获得HSSFTextbox的任何实例,只有HSSFObjectData的实例。 我的问题是,我可以从这些HSSFObjectDatas中提取输入文本框的值吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

恢复旧问题,但我有一个类,它从命名的textBox中读取Excel文本框字符串内容。以下是相关部分的摘录。请注意,“。trim()”很重要,因为形状名称似乎添加了训练空间。这给我带来了很多问题。

//Declarations
private HSSFWorkbook wb;
private HSSFWorkbook outputWb;
private HSSFSheet sheet;
private HSSFFont myFont;
private HSSFPatriarch pat;
private HSSFRichTextString str;
private List<HSSFShape> children;

//Constructor
try {
        NPOIFSFileSystem fs = new NPOIFSFileSystem(new File(IN_FILE_NAME));
        wb = new HSSFWorkbook(fs.getRoot(), true);
        sheet = wb.getSheet("Certificate");
        pat = (HSSFPatriarch) sheet.createDrawingPatriarch();
        children = pat.getChildren();

//Methods
private String getText(String textBoxName){
    return getRichText(textBoxName).toString().trim();
}

private  HSSFRichTextString getRichText(String textBoxName) {
    Iterator<HSSFShape> it = children.iterator();
    HSSFRichTextString returnString = null;
    while (it.hasNext()) {
        HSSFShape shape = it.next();
        if (shape.getShapeName().trim().equals(textBoxName)) {
            HSSFTextbox textbox = (HSSFTextbox) shape;
            returnString=textbox.getString();
        }
    }
    return returnString;
}