[英]How can I change TextBox in Excel with XSSF from Apache POI
I am using Apache POI to process Excel file. 我正在使用Apache POI处理Excel文件。 My Excel file has 2 TextBoxes for which I would like to read the text and change it. 我的Excel文件有2个TextBoxes,我想为其阅读文本并进行更改。 How is it possible with the XSSF model? XSSF模型怎么可能? I do not want to create a new TextBox- I know how to do this. 我不想创建一个新的TextBox,我知道该怎么做。 So far I was trying, but there is no TextBox anywhere there (that I can see). 到目前为止,我一直在尝试,但是那里没有任何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()){
}
So where are the TextBoxes? 那么TextBoxes在哪里?
Here's what I did to obtain references to Textboxes and change their contents in POI 3.10. 这是我获取文本框引用并在POI 3.10中更改其内容的方法。
For XSSF (untested): 对于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
}
}
For HSSF: 对于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);
}
}
It doesn't seem like this solution is very flexible though since setting different values for different Textboxes would require some conditional logic. 尽管由于为不同的文本框设置不同的值将需要一些条件逻辑,所以该解决方案似乎并不十分灵活。 Luckily for me, I was merely changing all of the Textboxes to the same text. 对我来说幸运的是,我只是将所有文本框更改为相同的文本。
Adapted from: Obtain textbox value from Excel in Java 改编自: 从Java中的Excel获取文本框值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.