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

我正在使用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,没有选项来configuration这个,因为你不能修改在导出过程中使用的Context和Transformer对象。

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

  1. 例如,使用Transformer setIgnoreColumnPropssetIgnoreRowProps方法来忽略列/行宽度

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