Java使用POI 动态创建excel table表格样式等



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;


public class MSExcelManager {

/*
* Excel文档
*/
private HSSFWorkbook workBook;

private HSSFSheet sheet;

private HSSFRow row = null;

private HSSFCell cell = null;

private short encoding = HSSFWorkbook.ENCODING_UTF_16;
private int cellType = HSSFCell.CELL_TYPE_STRING;
private HSSFCellStyle titleStyle;
private HSSFCellStyle titleStyle1;
private HSSFCellStyle titleStyle2;
private HSSFCellStyle tableStyle;
private HSSFCellStyle contentStyle;
private HSSFCellStyle footStyle;
private Region region;
private HSSFPalette palette;

public MSExcelManager() {

workBook = new HSSFWorkbook();
sheet = workBook.createSheet();
workBook.setSheetName(0, "在线专家监控日志", encoding);
sheet.setVerticallyCenter(true);
sheet.setDefaultColumnWidth((short) 10);
// sheet.setDefaultRowHeightInPoints(21.75f);
palette = getColorStyle();
titleStyle = getTitleStyle();
titleStyle1 = getTitleStyle((short) 9);
titleStyle2 = getTitleStyle((short) 10);
tableStyle = getTableStyle();
contentStyle = getContentStyle();
footStyle = getFootStyle();
}

public static void test() {

String filePath = "F:\\workspace\\webapp\\template\\telpate_test.xls";

FileInputStream fis;
try {
fis = new FileInputStream(filePath);
POIFSFileSystem fs = new POIFSFileSystem(fis);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);

// Iterate over each row in the sheet
Iterator rows = sheet.rowIterator();
HSSFRow row = null;
for (; rows.hasNext();) {
row = (HSSFRow) rows.next();
System.out.println("Row #" + row.getRowNum());
// Iterate over each cell in the row and print out the cell"s
// content
Iterator cells = row.cellIterator();
HSSFCell cell = null;
for (; cells.hasNext();) {
cell = (HSSFCell) cells.next();
System.out.println("Cell #" + cell.getCellNum() + " "
+ cell.getCellStyle());

switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
default:
System.out.println("unsuported sell type");
break;
}
}
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* @param args
*/
public static void main(String[] args) {

// test();

List vistorList = new ArrayList();
ExpertConsult expertConsult11 = null;
for (int i = 1; i <= 17; i++) {
expertConsult11 = new ExpertConsult();
expertConsult11.setTimePoint("08:30");
expertConsult11.setTimePointTotal(2 * i);
vistorList.add(expertConsult11);
}

List expertList = new ArrayList();
ExpertConsult expertConsult1 = null;
for (int i = 1; i <= 12; i++) {

expertConsult1 = new ExpertConsult();
expertConsult1.setId(i);
expertConsult1.setName("张三四" + i);
expertConsult1.setLoginTime("2011-01-04 12:30:47");
expertConsult1.setLoginOutTime("2011-01-04 13:30:59");
expertConsult1.setAllNum(10);
expertConsult1.setReplyNum(3);
expertConsult1.setUnreplyNum(7);
expertList.add(expertConsult1);
}

MSExcelManager msExcel = new MSExcelManager();

String path = "F:\\workspace\\webcallSYWG6.0\\webapp\\template\\export\\"
+ new Date().getTime() + ".xls";

msExcel.write(msExcel.exportExcel(vistorList, expertList, null), path);
}

public HSSFPalette getColorStyle() {
HSSFPalette palette = workBook.getCustomPalette();
palette.setColorAtIndex((short) 9, (byte) (182), (byte) (221),
(byte) (232));
palette.setColorAtIndex((short) 10, (byte) (252), (byte) (213),
(byte) (180));
return palette;

}

/**
* 第一行的样式
*
* @return
*/
public HSSFCellStyle getFirstStyle() {

HSSFCellStyle style = workBook.createCellStyle();
HSSFFont font = workBook.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 18);// 设置字体大小
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
style.setWrapText(true);
style.setFont(font);
return style;
}

/**
* 标题行样式
*
* @return
*/
public HSSFCellStyle getTitleStyle() {

HSSFCellStyle style = workBook.createCellStyle();
HSSFFont font = workBook.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 12);// 设置字体大小
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上线居中
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setWrapText(true);
style.setFont(font);
return style;
}

/**
* 蓝色样式
*
* @return
*/
public HSSFCellStyle getTitleStyle(short index) {

HSSFCellStyle style = workBook.createCellStyle();
HSSFFont font = workBook.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 12);// 设置字体大小
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上线居中
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setWrapText(true);
style.setFont(font);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(index);
return style;
}

/**
* 表格样式
*
* @return
*/
public HSSFCellStyle getTableStyle() {

HSSFCellStyle style = workBook.createCellStyle();
HSSFFont font = workBook.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 12);// 设置字体大小
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上线居中
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setWrapText(true);
style.setFont(font);
return style;
}

/**
* 文本样式
*
* @return
*/
public HSSFCellStyle getContentStyle() {
HSSFCellStyle style = workBook.createCellStyle();
HSSFFont font = workBook.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上线居中
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setWrapText(true);
style.setFont(font);
return style;
}

/**
* 底部,签名样式
*
* @return
*/
public HSSFCellStyle getFootStyle() {

HSSFCellStyle style = workBook.createCellStyle();
HSSFFont font = workBook.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 11);// 设置字体大小
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
style.setFont(font);
return style;
}

public void createRow(int currentRow, int rowNum, int colNum,
HSSFCellStyle style) {

for (int rowIndex = currentRow; rowIndex < rowNum; rowIndex++) {
row = sheet.createRow(rowIndex);
for (short cellIndex = 0; cellIndex < colNum; cellIndex++) {
cell = row.createCell(cellIndex);
cell.setEncoding(encoding);
if (style != null) {
cell.setCellStyle(style);
}
cell.setCellType(cellType);
cell.setCellValue("");
}
}
}

public HSSFRow getRow(int rowIndex) {
return sheet.getRow(rowIndex);
}

public void setValue(int rowIndex, int colIndex, String value,
HSSFCellStyle style, int type) {
HSSFRow row = sheet.getRow(rowIndex);
HSSFCell cell = row.getCell((short) colIndex);
cell.setCellType(type);
if (style != null) {
cell.setCellStyle(style);
}
cell.setCellValue(value);
}

public int getLastRowNum() {
return sheet.getLastRowNum();
}

public void mergedRegion(int rowFrom, int colFrom, int rowTo, int colTo) {
region = new Region(rowFrom, (short) colFrom, rowTo, (short) colTo);
sheet.addMergedRegion(region);
}

public String getTitle() {

StringBuffer title = new StringBuffer();

Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DATE);
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
String weekStr[] = new String[] { "日", "一", "二", "三", "四", "五", "六" };

title.append("监控日志——专家在线(");
title.append(year + "年");
title.append(month + "月");
title.append(day + "日 周");
title.append(weekStr[week] + ")");
return title.toString();
}

/**
* 报表导出excel格式
*
* @param vistorList
* @param expertList
* @return
*/
public HSSFWorkbook exportExcel(List vistorList,
List expertList, String title) {

// 创建标题行,1行10列
createRow(0, 1, 10, getFirstStyle());
getRow(0).setHeightInPoints((short) 35);
// 合并标题行
mergedRegion(0, 0, 0, 9);
// 填充标题行
if (title == null || title.equals("")) {
setValue(0, 0, getTitle(), null, cellType);
} else {
setValue(0, 0, title, null, cellType);
}

// 创建访客表格,6行10列
createRow(1, 7, 10, tableStyle);
// 合并首列
mergedRegion(1, 0, 6, 0);
// 设置标题行
setValue(1, 0, "在线\n人数\n登记", titleStyle, cellType);

setValue(1, 1, "时间", titleStyle, cellType);
setValue(1, 2, "08:30", titleStyle1, cellType);
setValue(1, 3, "09:00", titleStyle1, cellType);
setValue(1, 4, "09:30", titleStyle1, cellType);
setValue(1, 5, "10:00", titleStyle1, cellType);
setValue(1, 6, "10:30", titleStyle1, cellType);
setValue(1, 7, "11:00", titleStyle1, cellType);
setValue(1, 8, "11:30", titleStyle1, cellType);
setValue(1, 9, "12:00", titleStyle1, cellType);
setValue(2, 1, "人数", titleStyle, cellType);
setValue(3, 1, "时间", titleStyle, cellType);
setValue(3, 2, "12:30", titleStyle1, cellType);
setValue(3, 3, "13:00", titleStyle1, cellType);
setValue(3, 4, "13:30", titleStyle1, cellType);
setValue(3, 5, "14:00", titleStyle1, cellType);
setValue(3, 6, "14:30", titleStyle1, cellType);
setValue(3, 7, "15:00", titleStyle1, cellType);
setValue(3, 8, "15:30", titleStyle1, cellType);
setValue(3, 9, "16:00", titleStyle1, cellType);
setValue(4, 1, "人数", titleStyle, cellType);
setValue(5, 1, "时间", titleStyle, cellType);
setValue(5, 2, "16:30", titleStyle1, cellType);
setValue(5, 3, "17:00", titleStyle1, cellType);
setValue(5, 4, "17:30", titleStyle1, cellType);
setValue(5, 5, "18:00", titleStyle1, cellType);
setValue(5, 6, "18:30", titleStyle1, cellType);
setValue(5, 7, "19:00", titleStyle1, cellType);
setValue(5, 8, "19:30", titleStyle1, cellType);
setValue(5, 9, "20:00", titleStyle1, cellType);
setValue(6, 1, "人数", titleStyle, cellType);

ExpertConsult vistor = null;
// 动态设置统计访客人数
if (vistorList != null && !vistorList.isEmpty()) {
for (int i = 0; i < vistorList.size(); i++) {
vistor = vistorList.get(i);
setValue(i / 8 * 2 + 2, (i % 8 + 2), vistor.getTimePointTotal()
+ "", contentStyle, cellType);
}
}
// 创建在线专家表格,1行10列
createRow(7, 8, 10, tableStyle);
int lastRowNum = getLastRowNum();
// 设置标题行
setValue(lastRowNum, 0, "专家\n考核", titleStyle, cellType);
setValue(lastRowNum, 1, "姓名", titleStyle2, cellType);
setValue(lastRowNum, 2, "上线时间", titleStyle2, cellType);
setValue(lastRowNum, 3, "下线时间", titleStyle2, cellType);
setValue(lastRowNum, 4, "提答数量", titleStyle2, cellType);
setValue(lastRowNum, 5, "回答数量", titleStyle2, cellType);
setValue(lastRowNum, 6, "回答率", titleStyle2, cellType);
setValue(lastRowNum, 7, "回答质量", titleStyle2, cellType);
setValue(lastRowNum, 8, "实际回答时间", titleStyle2, cellType);

if (expertList != null && !expertList.isEmpty()) {
createRow(8, 8 + expertList.size(), 10, tableStyle);
} else {
createRow(8, 9, 10, tableStyle);
}

lastRowNum = getLastRowNum();
// 合并首列
mergedRegion(7, 0, lastRowNum, 0);
for (int i = 7; i <= lastRowNum; i++) {
// 合并尾列
mergedRegion(i, 8, i, 9);
}

int totalAllNum = 0;
int totalReplyNum = 0;
double totalReplyRate = 0.00d;
NumberFormat percentFormat = NumberFormat.getPercentInstance();
percentFormat.setMaximumIntegerDigits(2);
percentFormat.setMaximumFractionDigits(2);

ExpertConsult expert = null;
// 动态设置在线专家信息
if (expertList != null && !expertList.isEmpty()) {
for (int i = 0; i < expertList.size(); i++) {
expert = expertList.get(i);
String loginTime = expert.getLoginTime();
if (loginTime == null || loginTime.equals("")) {
loginTime = "--";
} else {
loginTime = loginTime.substring(11, 16);
}

String loginOutTime = expert.getLoginOutTime();
if (loginOutTime == null || loginOutTime.equals("")) {
loginOutTime = "--";
} else {
loginOutTime = loginOutTime.substring(11, 16);
}
setValue(8 + i, 1, expert.getName(), contentStyle, cellType);
setValue(8 + i, 2, loginTime, contentStyle, cellType);
setValue(8 + i, 3, loginOutTime, contentStyle, cellType);
setValue(8 + i, 4, expert.getAllNum() + "", contentStyle,
cellType);
setValue(8 + i, 5, expert.getReplyNum() + "", contentStyle,
cellType);
BigDecimal b = new BigDecimal(expert.getReplyRate());
double bb = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
setValue(8 + i, 6, bb + "%",contentStyle, cellType);
totalAllNum += expert.getAllNum();
totalReplyNum += expert.getReplyNum();
}
}
if (totalAllNum > 0) {
totalReplyRate = (double) totalReplyNum / (double) totalAllNum
* 100;
}
BigDecimal b = new BigDecimal(totalReplyRate);
totalReplyRate = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();

// 创建统计部分
createRow(lastRowNum + 1, lastRowNum + 5, 10, tableStyle);

// lastRowNum = getLastRowNum();
mergedRegion(lastRowNum + 1, 0, lastRowNum + 4, 0);

mergedRegion(lastRowNum + 1, 1, lastRowNum + 2, 3);
mergedRegion(lastRowNum + 1, 4, lastRowNum + 2, 6);
mergedRegion(lastRowNum + 1, 7, lastRowNum + 2, 9);

mergedRegion(lastRowNum + 3, 1, lastRowNum + 4, 3);
mergedRegion(lastRowNum + 3, 4, lastRowNum + 4, 6);
mergedRegion(lastRowNum + 3, 7, lastRowNum + 4, 9);

setValue(lastRowNum + 1, 0, "回答\n问题\n情况", titleStyle, cellType);
setValue(lastRowNum + 1, 1, "当天提问总量", titleStyle2, cellType);
setValue(lastRowNum + 1, 4, "当天回答总量", titleStyle2, cellType);
setValue(lastRowNum + 1, 7, "回答率", titleStyle2, cellType);

setValue(lastRowNum + 3, 1, totalAllNum + "", contentStyle, cellType);
setValue(lastRowNum + 3, 4, totalReplyNum + "", contentStyle, cellType);

setValue(lastRowNum + 3, 7, totalReplyRate + "%", contentStyle,
cellType);


lastRowNum = getLastRowNum();
createRow(lastRowNum + 1, lastRowNum + 6, 10, footStyle);
mergedRegion(lastRowNum + 2, 5, lastRowNum + 2, 6);
setValue(lastRowNum + 2, 5, "责任编辑签名:", footStyle, cellType);
setValue(lastRowNum + 2, 7, "(日)", footStyle, cellType);

mergedRegion(lastRowNum + 3, 5, lastRowNum + 3, 6);
setValue(lastRowNum + 3, 7, "(夜)", footStyle, cellType);

mergedRegion(lastRowNum + 5, 5, lastRowNum + 5, 6);
setValue(lastRowNum + 5, 5, "日期:", footStyle, cellType);

setValue(lastRowNum + 5, 7, "年", footStyle, cellType);
setValue(lastRowNum + 5, 8, "月", footStyle, cellType);
setValue(lastRowNum + 5, 9, "日", footStyle, cellType);
return workBook;
}

public void write(HSSFWorkbook workBook, String path) {

FileOutputStream fos;
try {
fos = new FileOutputStream(path);
workBook.write(fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

你可能感兴趣的:(2011年)