我正在使用apache-poi动态创建一个新的xlsx文件.任何列都可以包含不同的值类型(数字,字符串,布尔值,...).在将数据插入poi文档时,我根据数据类型设置CellStyles:
public final XSSFCellStyle cellStyleString;
public final XSSFCellStyle cellStyleNumber;
public final XSSFCellStyle cellStyleDate;
public final XSSFCellStyle cellStyleHeader;
Run Code Online (Sandbox Code Playgroud)
这是我的标题行的样子:
| | | | Shared Header |
| H1| H2| H3|SH1|SH2|SH3|SH4|
Run Code Online (Sandbox Code Playgroud)
有"简单"标题和"共享标题",其中包含"子标题".共享标头位于合并的单元中.
不,我希望列的左边框和列SH1的右边框SH4强调分组.但是,由于任何列都可以包含所有单元格的混合,似乎我必须创建像CellStyles一样
public final XSSFCellStyle cellStyleString;
public final XSSFCellStyle cellStyleStringBorderLeft;
public final XSSFCellStyle cellStyleStringBorderRight;
//and so on for the other styles...
Run Code Online (Sandbox Code Playgroud)
此外,可能有嵌套的共享标题,我想通过不同的边框大小区分.所以我需要类似的东西
public final XSSFCellStyle cellStyleString;
public final XSSFCellStyle cellStyleStringBorderLeftThickLine;
public final XSSFCellStyle cellStyleStringBorderRightThickLine;
public final XSSFCellStyle cellStyleStringBorderLeftThinLine;
public final XSSFCellStyle cellStyleStringBorderRightThinLine;
//and so on for the other styles...
Run Code Online (Sandbox Code Playgroud)
无论现有样式如何,是否有更优雅的方式来设置列的边框?
编辑
虽然我更喜欢干净简单的方法,并且为了最大限度地减少创建的样式的数量,我对HSSFOptimiser进行了简化,它消除了重复的单元格样式.我不知道那堂课.即使我更喜欢避免这个实用程序,它也适合这个问题,值得在这里提到.
我即将结束对POI的增强,这将使您可以使用其特定样式填充值,然后在它们周围绘制边框,而无需手动创建所有必需的样式.在平均时间,有一种方法可以使用它CellUtil.setCellStyleProperties().这允许您向CellStyle单元格已存在的属性添加一组属性.
来自HSSF/XSSF的POI快速指南:
Workbook workbook = new XSSFWorkbook(); // OR new HSSFWorkbook()
Sheet sheet = workbook.createSheet("Sheet1");
Map<String, Object> properties = new HashMap<String, Object>();
// create your spreadsheet without borders
...
// create property set for vertical borders
properties.put(CellUtil.BORDER_LEFT, CellStyle.BORDER_MEDIUM);
properties.put(CellUtil.BORDER_RIGHT, CellStyle.BORDER_MEDIUM);
// Apply the borders to a 3x3 region starting at D4
for (int ix=3; ix <= 5; ix++) {
row = sheet.createRow(ix);
for (int iy = 3; iy <= 5; iy++) {
cell = row.createCell(iy);
CellUtil.setCellStyleProperties(cell, properties);
}
}
Run Code Online (Sandbox Code Playgroud)
这允许您基本上填写电子表格,然后一次绘制一个单元格的边框.请注意,如果所有边框都相似(全部为THIN),那么这将适用于整个范围.但是,如果要在表格外部绘制MEDIUM边框,则必须创建一些其他属性集.请注意,您不必使用createRow()和createCell()行和细胞已经在您的电子表格.这将解决合并的单元格.
注意:CellUtil.setCellStyleProperties()出现在POI 3.14中,允许您在单个镜头中添加多个单元格属性,从而避免创建多个未使用的样式.旧版本一次CellUtil.setCellStyleProperty()设置一个属性,并且作为意外结果,CellStyle在电子表格中创建中间对象,结果从未使用过.这可能是较大的纸张中的问题.
编辑:
PropertyTemplate是在POI 3.15中添加的新对象,它允许您为单元格定义一组边框并将其标记到要应用它的任何图纸上.此对象类似于创建预打印表单以覆盖数据.有关如何使用的更多信息,请参阅POI电子表格快速指南PropertyTemplate.