Apache POI Excel 单元格属性
有时我们想要创建一个具有基本样式的电子表格,然后将特殊样式应用到某些单元格,例如在一系列单元格周围绘制边框或为某个区域设置填充。Apache POI 提供了CellUtil.setCellProperties,它允许我们这样做而无需在我们的电子表格中创建一堆不必要的中间样式。
属性创建为Map并应用于单元格。
让我们看一个示例,其中我们将特殊样式应用于特定单元格。
Apache POI Excel 单元格属性示例
package com.yiidian;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
public class CellPropertiesExample {
public static void main(String[] args) throws Exception {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet");
Map<String, Object> properties = new HashMap<>();
// border around a cell
properties.put(CellUtil.BORDER_TOP, CellStyle.BORDER_MEDIUM);
properties.put(CellUtil.BORDER_BOTTOM, CellStyle.BORDER_MEDIUM);
properties.put(CellUtil.BORDER_LEFT, CellStyle.BORDER_MEDIUM);
properties.put(CellUtil.BORDER_RIGHT, CellStyle.BORDER_MEDIUM);
// Give it a color (RED)
properties.put(CellUtil.TOP_BORDER_COLOR, IndexedColors.RED.getIndex());
properties.put(CellUtil.BOTTOM_BORDER_COLOR, IndexedColors.RED.getIndex());
properties.put(CellUtil.LEFT_BORDER_COLOR, IndexedColors.RED.getIndex());
properties.put(CellUtil.RIGHT_BORDER_COLOR, IndexedColors.RED.getIndex());
// Apply the borders to the cell at B2
Row row = sheet.createRow(1);
Cell cell = row.createCell(1);
for (Map.Entry<String, Object> e : properties.entrySet()) {
CellUtil.setCellStyleProperty(cell, workbook, e.getKey(), e.getValue());
}
cell.setCellValue("First"); // 单元格值
// 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);
for (Map.Entry<String, Object> e : properties.entrySet()) {
CellUtil.setCellStyleProperty(cell, workbook, e.getKey(), e.getValue());
}
cell.setCellValue(ix + " * " + iy); // 单元格值
}
}
FileOutputStream fileOut = new FileOutputStream("yiidian.xls");
workbook.write(fileOut);
fileOut.close();
System.out.println("The end.");
}
}
输出结果为:
热门文章
优秀文章