/**
* Excel WorkBook对象类
* @author zhouqian
*
*/
public class ExcelWorkBook {
/** 工作簿 */
private static HSSFWorkbook workbook = new HSSFWorkbook();
/** 工作表 */
private HSSFSheet sheet;
/** 表头数据 */
private String[] tableHeader;
/**
* 构造函数
* @param workbookName 工作表名
* @param tableHeader 表头数据
*/
public ExcelWorkBook(String workbookName, String[] tableHeader) {
super();
this.tableHeader = tableHeader;
sheet = workbook.createSheet(workbookName);
}
/**
* 创建表头
* @param headerName
*/
public void createTableHeader(String headerName) {
HSSFHeader header = sheet.getHeader();
header.setCenter(headerName);
HSSFRow headerRow = sheet.createRow(0);
int cellNumber = tableHeader.length;
for (int i = 0; i < cellNumber; i++) {
HSSFCell headerCell = headerRow.createCell((short)i);
headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
headerCell.setCellValue(tableHeader[i]);
}
}
/**
* 创建行
* @param data 要写入的数据
* @param rowIndex 第rowIndex行
*/
public void createTableRow(String[] data, int rowIndex) {
HSSFRow row = sheet.createRow(rowIndex);
for (int i = 0; i < data.length; i++) {
HSSFCell cell = row.createCell((short)i);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(data[i]);
}
}
/**
* 创建整个Excel表
* @param headerName
*/
public void createExcelSheet(String headerName, String[][] data) {
this.createTableHeader(headerName);
String[] rowData;
for (int i = 0; i < data.length; i++) {
rowData = data[i];
createTableRow(rowData, i + 1);
}
}
/**
* 导出Excel表格
* @param os
* @throws IOException
*/
public void exportExcel(OutputStream os) throws IOException {
sheet.setGridsPrinted(true);
HSSFFooter footer = sheet.getFooter();
footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
workbook.write(os);
}
public HSSFSheet getSheet() {
return sheet;
}
public void setSheet(HSSFSheet sheet) {
this.sheet = sheet;
}
public String[] getTableHeader() {
return tableHeader;
}
public void setTableHeader(String[] tableHeader) {
this.tableHeader = tableHeader;
}
}