首页 > 解决方案 > 如何在 Apache POI XSSFChart 中旋转文本标签

问题描述

我正在尝试使用 Apache POI 库生成一个包含 Bar 聊天的 excel 文档。我想旋转 x 轴标签中的文本,但没有旋转文本的选项。这是我迄今为止尝试过的

XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing
                .createAnchor(0, 0, 0, 0, graphStartColumn, graphStartRow, graphEndColumn, graphEndRow);
 XSSFChart chart = drawing.createChart(anchor);

XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setTitle(report.getX().getLegend());
bottomAxis.getOrAddTextProperties().setBold(true);
// here I'm trying to add text rotation to x-axis labels, but I don't see an option in axis

XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
leftAxis.setTitle(report.getY().get(0).getLegend());
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

有谁知道如何在 x 轴上旋转文本?

标签: javaexcelspring-bootapache-poi

解决方案


尚不支持此功能XDDFCategoryAxis。但当然底层ooxml-schemas类支持它。

所以我们可以org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody从类别轴获取并在那里设置旋转属性。由于bottomAxis.getOrAddTextProperties()设置,我们可以肯定,TxPr已经有一个,还有一个BodyPr。所以我们不需要null检查这些。

唯一的额外挑战是轮换的价值。我们可以将旋转设置为 0 到 90 度和 0 到 -90 度。有 90 度的值为 5400000。

例子:

...
  bottomAxis.getOrAddTextProperties().setBold(true);

  java.lang.reflect.Field _ctCatAx = XDDFCategoryAxis.class.getDeclaredField("ctCatAx");
  _ctCatAx.setAccessible(true);
  org.openxmlformats.schemas.drawingml.x2006.chart.CTCatAx ctCatAx = (org.openxmlformats.schemas.drawingml.x2006.chart.CTCatAx)_ctCatAx.get(bottomAxis);
  org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody text = ctCatAx.getTxPr(); // there is a TxPr already because of bottomAxis.getOrAddTextProperties()

  int rotAngle = 0;
  //int plus90Deg = 5400000; rotAngle = plus90Deg;
  //int minus90Deg = -5400000; rotAngle = minus90Deg;
  //int plus45Deg = (int)Math.round(5400000/2d); rotAngle = plus45Deg;
  int minus45Deg = (int)Math.round(-5400000/2d); rotAngle = minus45Deg;

  text.getBodyPr().setRot(rotAngle); // there is a BodyPr already because of bottomAxis.getOrAddTextProperties()
...

推荐阅读