JXLS 忽略模板样式,我如何强制它保持模板文件中的列宽?

JXLS ignores template style, how can I force it to keep the column widths as they are in the template file?

我正在使用 JXLS 通过自定义模板生成 excel 文件。该模板只是库自带的标准网格导出模板,只是我更改了模板文件中某些列的宽度。我的代码大部分只是示例代码的副本。

 private void exportAsXLS(List<CalExportItem> exportItems, OutputStream os1) {

    try (InputStream is = CalDataExporter.class.getClassLoader().getResourceAsStream(TEMPLATE_FILEPATH)) {
        xlsExporter.registerGridTemplate(is);
        xlsExporter.gridExport(Arrays.asList(HEADERS), exportItems, FIELDS, os1);
    } catch (Exception e) {
        LOGGER.error("Exception exporting as XLS", e);
    }
}

我基本上只是复制了"SimpleExporter"样本

public class CalXlsExportHelper {

private static final Logger LOGGER = LoggerFactory.getLogger(CalXlsExportHelper.class);

private byte[] templateBytes;

public void registerGridTemplate(InputStream inputStream) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    byte[] data = new byte[4096];
    int count;
    while ((count = inputStream.read(data)) != -1) {
        os.write(data, 0, count);
    }
    templateBytes = os.toByteArray();
}

public void gridExport(Iterable headers, Iterable dataObjects, String objectProps, OutputStream outputStream) {
    InputStream is = new ByteArrayInputStream(templateBytes);
    Transformer transformer = TransformerFactory.createTransformer(is, outputStream);

    //******** key difference with SimpleExporter ********
    // Passing false to areaBuilder in order to prevent clearing of cells and loss of template style
    AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer, false);

    List<Area> xlsAreaList = areaBuilder.build();
    Area xlsArea = xlsAreaList.get(0);
    Context context = new Context();
    context.putVar("headers", headers);
    context.putVar("data", dataObjects);
    GridCommand gridCommand = (GridCommand) xlsArea.getCommandDataList().get(0).getCommand();
    gridCommand.setProps(objectProps);
    xlsArea.applyAt(new CellRef("Sheet1!A1"), context);
    try {
        transformer.write();
    } catch (IOException e) {
        LOGGER.error("Failed to write to output stream", e);
        throw new JxlsException("Failed to write to output stream", e);
    }
}

}

这就是我在模板文件中的内容:

Author:
jx:area(lastCell="A3")

jx:grid(lastCell="A3" headers="headers" data="data" areas=[A2:A2, A3:A3]  
   formatCells="String:A3,Integer:B3,Long:B3,Short:B3,Double:B3,Float:B3,BigDecimal:B3")

对于 SimpleExporter,没有选项可以配置它,因为您无法修改导出期间使用的 Context and Transformer 对象。

但如果您使用其他方式导出,您将有以下选项

  1. 使用 Transformer setIgnoreColumnPropssetIgnoreRowProps 方法忽略 column/row 宽度,例如

    ((PoiTransformer)transformer).setIgnoreColumnProps(true);
    ((PoiTransformer)transformer).setIgnoreRowProps(true);
    
  2. 使用Context.Config设置忽略所有源单元格样式 context.getConfig().setIgnoreSourceCellStyle(true)