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

时间:2016-06-20 12:12:53

标签: java excel apache-poi jxls

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

# This register will be created in 'examples' table (default table name)
Example.create! attribute: 'value'

# Las element from 'examples' table
Example.last

Example.within_table 'examples_copy' do
  # This one will be created in 'examples_copy' table
  Example.create! attribute: 'value'
  # Last register of 'examples_copy' table
  Example.last
end

我基本上只是复制了“SimpleExporter”样本

 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);
    }
}

}

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

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);
    }
}

1 个答案:

答案 0 :(得分:1)

使用SimpleExporter无法配置此选项,因为您无法修改导出期间使用的ContextTransformer个对象。

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

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

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