java生成Excel

public static void write(OutputStream outputStream, List<?> lists, List<Grid> grids) throws IOException {
// 初始一个workbook
HSSFWorkbook workbook = new HSSFWorkbook();


// 每个sheet表存60000条数据
int sheetNum = lists.size() / 60000;


// 循环创建多个sheet
for (int sheetIndex = 0; sheetIndex < sheetNum + 1; sheetIndex++) {
HSSFSheet sheet = workbook.createSheet("sheet" + sheetIndex);


// 创建表头
HSSFRow rowTitle = sheet.createRow(0);
int rowNum = 0;
for (Grid grid : grids) {
HSSFCell cell = rowTitle.createCell(rowNum);
cell.setCellValue(grid.getText());
rowNum++;
}


//数据量
int dataNum = 0;
if(sheetIndex == sheetNum){
dataNum = lists.size()-sheetIndex*60000;
}else{
dataNum = 60000;
}

// 创建多行
for (int rowIndex = 0; rowIndex < dataNum; rowIndex++) {
HSSFRow row = sheet.createRow(rowIndex + 1);


Object list = lists.get(rowIndex + sheetIndex*60000);
// 创建多列
int cellnum = 0;
for (Grid grid : grids) {
HSSFCell cell = row.createCell(cellnum);
Object value = getFieldValueByName(grid.getId(), list);
if (value == null) {
cell.setCellValue("");
} else {
cell.setCellValue(value.toString());
}


cellnum++;
}
}
}


workbook.write(outputStream);

}


public static void ExcelExport(List<?> lists, List<Grid> grids, HttpServletResponse response, HttpServletRequest request) {
OutputStream outputStream = null;
try {
String rootPath = request.getSession().getServletContext().getRealPath("/");
String path = rootPath + "Download";
File filePath =new File(path);    
//如果文件夹不存在则创建    
if  (!filePath .exists()  && !filePath .isDirectory())      
{       
   filePath .mkdir();    


String fileName = filePath + "\\" + (new Date()).getTime() + ".xls";
File file = new File(fileName);
outputStream = new FileOutputStream(file);
//生成Excel
write(outputStream, lists, grids);


//弹出下载框
download(fileName, response);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值