使用POI操作Excel表格样式
包括:合并单元格,设置字体大小、颜色、背景色
首先通过练习API发现,CellStyle对象有两种操作方式来获得
1.可以通过WorkBook.createCellStyle(),这样得到的CellStyle为全新的CellStyle对象。如果是希望在原有的样式上添加新的样式,显然这种方式是不可取的,应该通过下面方法得到CellStyle
2.Cell.getCellStyle(),得到当前单元格的样式对象
全部源码
@Test
public void testCellStyle() throws Exception{
/*
* 03版为例:下面开始学习如何给单元格添加样式,如:合并单元格,设置字体(大小),设置前景色
* 1.合并第一行第一列到第五列单元格
* 2.得到A1单元格
* 3.设置该单元格的样式(字体大小、加粗,背景,边框)
* 4.设置单元格内容
*/
//创建工作簿(workbook)
HSSFWorkbook workBook=new HSSFWorkbook();
//创建工作表(可以设置工作表名)
HSSFSheet sheet=workBook.createSheet("hello world");
//合并单元格(合并第一行的第一列到第五列)
CellRangeAddress cellRangeAddress=new CellRangeAddress(1, 1, 1, 9);
//合并单元格属于工作表,所以设置到表
sheet.addMergedRegion(cellRangeAddress);//返回合并的单元格的索引
//创建行
HSSFRow row = sheet.createRow(1);//索引从0开始
//创建单元格
HSSFCell cell = row.createCell(1);//索引从0开始
//////////////////////////使用样式///////////////////////////////////
//设置边框“田”
int firstRow=cellRangeAddress.getFirstRow();
int lastRow=cellRangeAddress.getLastRow();
int firstColumn=cellRangeAddress.getFirstColumn();
int lastColumn=cellRangeAddress.getLastColumn();
for(int i=firstRow;i<=lastRow;i++){
for(int j=firstColumn;j<=lastColumn;j++){
setArroundBorder(workBook, sheet, i, j);
}
}
//得到单元格已有样式对象
CellStyle cellStyle=cell.getCellStyle();
//设置水平居中
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//设置颜色前必须的步骤(设置填充模式)
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);//前景色的填充模式
//设置前景色(即为单元格背景)
cellStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
//创建一个字体对象
Font font= workBook.createFont();
//设置为粗体
font.setBold(true);
//设置字体大小,注意API名inPoint
font.setFontHeightInPoints((short)20);
//设置字体颜色
font.setColor(IndexedColors.RED.index);
//添加字体到样式
cellStyle.setFont(font);
//将样式设置到单元格
cell.setCellStyle(cellStyle);
//////////////////////////样式操作结束///////////////////////////////////
//5.设置单元格内容
cell.setCellValue("边框、加粗、背景,水平垂直居中");
//以上操作数据位于内存中,下面写入文档
//注意:write接收参数为OutputStream,说明在jsp可以直接输入到浏览器(下载excel)
FileOutputStream file = new FileOutputStream("F:\\03excel.xls");
workBook.write(file);
//关闭(先开后关原则)
file.close();
workBook.close();
}
//抽取的实现粗边框的方法
private void setArroundBorder(HSSFWorkbook workBook, HSSFSheet sheet,
int row, int column) {
HSSFCell currentCell = sheet.getRow(row).getCell(column);
if(currentCell==null){
currentCell=sheet.getRow(row).createCell(column);
}
HSSFCellStyle currentStyle = workBook.createCellStyle();
short color = IndexedColors.BLACK.index;
short style=HSSFCellStyle.BORDER_MEDIUM;
currentStyle.setBorderBottom(style);
currentStyle.setBottomBorderColor(color);
currentStyle.setBorderTop(style);
currentStyle.setTopBorderColor(color);
currentStyle.setBorderLeft(style);
currentStyle.setLeftBorderColor(color);
currentStyle.setBorderRight(style);
currentStyle.setRightBorderColor(color);
currentCell.setCellStyle(currentStyle);
}