如何基于页面坐标计算XLSX列宽(Birt自定义发射器场景)
核心错误点
- 直接使用
coordinates[i]单个坐标值计算列宽:page.getCoordinates()返回的是页面水平方向分隔线的绝对坐标(单位为千分之一英寸),列宽为相邻两个坐标的差值,而非单个坐标值本身。 - 原有
countXlsxColWidth方法逻辑不符合Office Open XML的XLSX列宽计算标准,换算规则偏差导致结果不符合预期。
修正后实现代码
@Override public void endSheet(Page page, String orientation, int pageWidth, int pageHeight, float leftMargin, float rightMargin, float topMargin, float bottomMargin) { double[] coordinates = page.getCoordinates(); // 列数为坐标点数量减1,列宽取相邻坐标的差值 for (int i = 0; i < coordinates.length - 1; i++) { // 坐标单位转英寸 double colWidthInch = (coordinates[i+1] - coordinates[i]) / 1000.0D; // 按96DPI换算为XLSX标准列宽 int xlsxColWidth = calculateXlsxColumnWidth(colWidthInch, 96); this.sheet.setColumnWidth(i, xlsxColWidth * 256); } }
public static int calculateXlsxColumnWidth(double widthInInch, int dpi) { // 英寸转像素 double widthInPixel = widthInInch * dpi; // XLSX默认字体(Calibri 11号)单字符宽度约为7像素 double defaultCharWidth = 7.0D; // 扣除Excel内置边距偏移后换算为字符宽度单位 double widthInChar = (widthInPixel - 5) / defaultCharWidth; // 保留1位小数返回 return (int) Math.round(widthInChar * 10) / 10; }
适配调整说明
- 若你配置的Excel导出默认字体不是Calibri 11号,需要调整
defaultCharWidth参数:比如使用宋体12号时,将值改为8即可。 - 若导出后存在内容轻微截断的情况,可在最终返回值上加1~2的偏移量做补偿。
内容的提问来源于stack exchange,提问作者user3458271
相关产品推荐
相关产品推荐

