poi报表实现,导出到excel文件

package cn.lmj.utils;


import java.io.OutputStream;
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.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;


public class ExcelFileGenerator
{
private final int SPLIT_COUNT = 1500;// Excel每个工作簿的行数


private List<String> fieldName = null; // Excel标题数据集


private List<List<String>> fieldData = null; // Excel数据内容


private HSSFWorkbook workbook = null;


public ExcelFileGenerator(List<String> fieldName,
List<List<String>> fieldData)
{
this.fieldName = fieldName;
this.fieldData = fieldData;
}


public HSSFWorkbook createWorkbook()
{
workbook = new HSSFWorkbook();
int rows = fieldData.size();
int sheetNum = 0;


if (rows % SPLIT_COUNT == 0)
{
sheetNum = rows / SPLIT_COUNT;
}
else
{
sheetNum = rows / SPLIT_COUNT + 1;
}


for (int i = 1; i <=sheetNum; i++)
{
HSSFSheet sheet = workbook.createSheet("Page" + i);
HSSFRow headRow = sheet.createRow((short) 0);
for (int j = 0; j < fieldName.size(); j++)
{
HSSFCell cell = headRow.createCell((short) j);
// 添加样式
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
// 设置所有单元格的宽度
sheet.setColumnWidth((short) j, (short) 6000);
// 创建样式(使用工作本的对象创建)
HSSFCellStyle cellStyle = workbook.createCellStyle();
// 创建字体的对象
HSSFFont font = workbook.createFont();
// 将字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 设置字体的颜色
short color = HSSFColor.RED.index;
font.setColor(color);
// 将新设置的字体属性放置到样式中
cellStyle.setFont(font);
if (fieldName.get(j) != null)
{
cell.setCellStyle(cellStyle);
cell.setCellValue(fieldName.get(j));
}
else
{
cell.setCellStyle(cellStyle);
cell.setCellValue("-");
}
}


for (int k = 0; k < (rows < SPLIT_COUNT ? rows : SPLIT_COUNT); k++)
{
HSSFRow row = sheet.createRow((short) (k + 1));
List<String> rowList = fieldData.get((i - 1) * SPLIT_COUNT + k);


for (int n = 0; n < rowList.size(); n++)
{
HSSFCell cell = row.createCell((short) n);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
if (rowList.get(n) != null)
{
cell.setCellValue(rowList.get(n));
}
else
{
cell.setCellValue("");
}
}
}
}


return workbook;
}


public void expordExcel(OutputStream os) throws Exception
{
workbook = createWorkbook();
workbook.write(os);
os.close();
}
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值