HSSFCellStyle类定义

这一节开始介绍如何通过POI来进行单元格格式的设定。设定格式使用「HSSFCellStyle」类,关于它的类定义如下:

  • java.lang.Object
  • org.apache.poi.hssf.usermodel.HSSFCellStyle
  • public class HSSFCellStyle extends java.lang.Object

它有一个构造方法。

构造方法
protected HSSFCellStyle(short index, ExtendedFormatRecord rec)
Creates new HSSFCellStyle why would you want to do this??

虽然有构造方法,但却是protected的,所以不能直接使用,要通过一个工作簿workbook来生成格式对象。

在POI里,格式好像是以workbook为单位来管理的,所以要先作成一个格式对象,保存在workbook里,然后再对已生成好的单元格进行设定。

在单元格里指定格式

要作成一个格式对象,可以使用「HSSFWorkbook」类的「createCellStyle」方法。

createCellStyle
public HSSFCellStyle createCellStyle()
create a new Cell style and add it to the workbook's style table 

Returns:
  the new Cell Style object

另外,要取出现有的格式对象的话,使用「HSSFWorkbook」类的「getCellStyleAt」方法,这个方法有参数,是被保存格式的INDEX号。

getCellStyleAt
public HSSFCellStyle getCellStyleAt(short idx)
get the cell style object at the given index 

Parameters:
  idx - index within the set of styles
Returns:
  HSSFCellStyle object at the index

还有,对于某一个单元格,也可以取出它的格式对象。这时要使用「HSSFCell」类的「getCellStyle」方法。

getCellStyle
public HSSFCellStyle getCellStyle()
get the style for the cell. This is a reference to a cell style
contained in the workbook object.

这样的话,不管是新创建的或者是从现有的单元格里取出来的格式对象,都可以用来对某一个单元格进行格式的设定。设定方法使用「HSSFCell」类的「setCellStyle」方法。

setCellStyle
public void setCellStyle(HSSFCellStyle style)
set the style for the cell. The style should be an HSSFCellStyle
created/retreived from the HSSFWorkbook. 

Parameters:
  style - reference contained in the workbook

示例程序

关于格式的详细设定方法,下几节再讲,先做个示例程序来看看。

import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;

public class POISample{
  public static void main(String[] args){
    HSSFWorkbook workbook = new HSSFWorkbook();

    HSSFSheet sheet = workbook.createSheet();
    HSSFRow row = sheet.createRow(1);

    HSSFCell cell = row.createCell((short)0);
    cell.setCellValue("sample");

    HSSFCellStyle style = workbook.createCellStyle();
    style.setFillBackgroundColor(HSSFColor.WHITE.index);
    style.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
    style.setFillPattern(HSSFCellStyle.THICK_HORZ_BANDS);

    cell.setCellStyle(style);

    FileOutputStream out = null;
    try{
      out = new FileOutputStream("sample.xls");
      workbook.write(out);
    }catch(IOException e){
      System.out.println(e.toString());
    }finally{
      try {
        out.close();
      }catch(IOException e){
        System.out.println(e.toString());
      }
    }
  }
}

按上面程序,在某一个单元格里设定了顔色。运行结果如下:

格式设定

好了,从下一节开始详细介绍单元格格式的设定。

Leave a Reply

We will keep You Updated...
Sign up to receive breaking news
as well as receive other site updates!
Sponsors


Featured Video
Enter featured video code here.
Sponsors
Enter Google Analytics Code Here