//生成docx
@Test
public void test5() throws Exception {
License license = new License();
license.setLicense("./lib/newlic.lic");
Document doc = new Document();
doc.removeAllChildren();
Section section = new Section(doc);
Body body = new Body(doc);
doc.appendChild(section);
section.appendChild(body);
body.appendChild(addTable(doc));
doc.save("./file/docx.docx");
}
public Table addTable(Document doc) throws Exception {
Table table = new Table(doc);
for (int i = 0; i < 3; i++) {
Row row = new Row(doc);
row.getRowFormat().setHeight(50);
for (int j = 0; j < 3; j++) {
Cell cell = new Cell(doc);
cell.getCellFormat().setPreferredWidth(PreferredWidth.fromPoints(20));
Paragraph paragraph = new Paragraph(doc);
Run run = new Run(doc);
run.setText("单元格" + i + j);
paragraph.appendChild(run);
cell.appendChild(paragraph);
row.appendChild(cell);
}
table.appendChild(row);
}
return table;
}
@humanhuman, 您需要为您的表格设置 AutoFitBehavior.FIXED_COLUMN_WIDTHS:
public Table addTable(Document doc) throws Exception {
Table table = new Table(doc);
for (int i = 0; i < 3; i++) {
Row row = new Row(doc);
row.getRowFormat().setHeight(50);
for (int j = 0; j < 3; j++) {
Cell cell = new Cell(doc);
cell.getCellFormat().setPreferredWidth(PreferredWidth.fromPoints(20));
Paragraph paragraph = new Paragraph(doc);
Run run = new Run(doc);
run.setText("单元格" + i + j);
paragraph.appendChild(run);
cell.appendChild(paragraph);
row.appendChild(cell);
}
table.appendChild(row);
}
// 请添加这一行
table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);
return table;
}
请参考我们的文档: