个性化阅读
专注于IT技术分析

apache poi excel单元格属性

本文概述

有时,我们希望创建具有基本样式的电子表格,然后将特殊样式应用于某些单元格,例如围绕一系列单元格绘制边框或设置区域的填充。 Apache POI提供了CellUtil.setCellProperties,它使我们能够执行此操作而无需在电子表格中创建一堆不必要的中间样式。

将属性创建为Map并将其应用于单元格。

让我们看一个示例,其中我们对某些单元格应用特殊样式。

Apache POI Excel单元格属性示例

package poiexample;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellUtil;
public class CellPropertiesExample {
	public static void main(String[] args) {
		try (OutputStream os = new FileOutputStream("srcmini.xls")) {
			 Workbook workbook = new HSSFWorkbook();
			 Sheet sheet = workbook.createSheet("Sheet");
			 HashMap<String, Object> properties = new HashMap<String, Object>();
			 // Set border around the cell
			 properties.put(CellUtil.BORDER_TOP, BorderStyle.MEDIUM);
			 properties.put(CellUtil.BORDER_BOTTOM, BorderStyle.MEDIUM);
			 properties.put(CellUtil.BORDER_LEFT, BorderStyle.MEDIUM);
			 properties.put(CellUtil.BORDER_RIGHT, BorderStyle.MEDIUM);
			 // Set 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
			 Row row   = sheet.createRow(2);
			 Cell cell = row.createCell(2);
			 CellUtil.setCellStyleProperties(cell, properties);
			 // Apply the borders to a 3x3 region starting at D4
			 for (int i=3; i <= 5; i++) {
			   row = sheet.createRow(i);
			   for (int j = 3; j <= 5; j++) {
			     cell = row.createCell(j);
			     CellUtil.setCellStyleProperties(cell, properties);
			   }
			 }
			 workbook.write(os);
		}catch(Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

输出:

赞(0)
未经允许不得转载:srcmini » apache poi excel单元格属性

评论 抢沙发

评论前必须登录!