You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache POI 5导出30+列JDBC结果集到Word列被隐藏如何解决

根因说明

默认生成的Word文档为A4纵向布局,页面宽度不足以容纳30+列的表格,超出页面宽度的部分会被自动截断隐藏,调整页面布局+优化表格配置即可解决该问题。

解决步骤

1. 配置页面为横向/自定义页面尺寸

在创建XWPFDocument实例后,新增页面参数配置代码:

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocument1;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageSz;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STPageOrientation;
import java.math.BigInteger;

// ... 原有代码
XWPFDocument document = new XWPFDocument();

// 新增页面配置开始
CTDocument1 ctDoc = document.getDocument();
CTBody ctBody = ctDoc.getBody();
CTSectPr sectPr = ctBody.isSetSectPr() ? ctBody.getSectPr() : ctBody.addNewSectPr();
CTPageSz pageSz = sectPr.isSetPgSz() ? sectPr.getPgSz() : sectPr.addNewPgSz();

// 配置为A4横向
pageSz.setW(BigInteger.valueOf(16840)); // 页面宽度(单位:缇,1缇=1/1440英寸)
pageSz.setH(BigInteger.valueOf(11900)); // 页面高度
pageSz.setOrient(STPageOrientation.LANDSCAPE); // 设置为横向布局
// 若需要自定义更大尺寸,直接调整w、h参数即可
// 新增页面配置结束

2. 调整表格宽度规则

原有table.setWidth("100%")在多列场景下会自动压缩列宽导致内容隐藏,替换为自动适配规则:

// 移除原有 table.setWidth("100%");
// 替换为以下配置
table.setWidthType(TableWidthType.AUTO);
// 可按需设置每列最小宽度,避免内容挤压
for (int i = 0; i < columnsNumber; i++) {
    table.setColumnWidth(i, 1200); // 单位为缇,可自行调整数值
}

可选优化方案

如果30+列在横向A4布局下仍然无法完整展示,可选择以下方案:

  • 进一步调大自定义页面的宽度参数
  • 统一缩小表格内文字的字号
  • 将表格按列拆分后分开展示

内容的提问来源于stack exchange,提问作者Ladu anand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:36:05