poi导出excel 损坏_使用POI导出Excel例子与常见问题

这篇博客介绍了如何使用Apache POI库导出Excel文件,并提供了一个具体的Java代码示例。文章指出,在导出过程中要注意避免文件损坏,特别是要确保前端以表单方式提交,而不是通过Ajax,因为Ajax无法处理流作为返回值,可能导致无法正常下载。
摘要由CSDN通过智能技术生成

代码

function toExcel(){

$("#formExcel").submit();

}

@RequestMapping(value="/toExcel",method=RequestMethod.POST)

public String toExcel(HttpServletResponse response, String fileName, String tableName, String type, String where){

if (StringUtils.isNotEmpty(fileName) && StringUtils.isNotEmpty(tableName) && StringUtils.isNotEmpty(type)) {

inteQueryService.toExcel(response,fileName,tableName,type,where);

return null;

}

return null;

}

public static void toExcel(HttpServletResponse response,List> lists,String name,String[] strArr){

List[] totals = splitList(lists,65000);

// 创建工作簿

HSSFWorkbook wb = new HSSFWorkbook();

// 由工作簿创建工作表

for (int j = 0; j < totals.length; j++) {

HSSFSheet sheet = wb.createSheet("sheet"+(j+1));

// 在工作表中创建行

HSSFRow row = sheet.createRow(0);

// 创建单元格,设置每个单元格的字段名

HSSFCell cell = null;

for (int i = 0; i < strArr.length; i++) {

cell = row.createCell(i);

cell.setCellValue(strArr[i]);

}

List> list = totals[j];

for (int i = 0; i < list.size(); i++) {

Iterator iter = list.get(i).entrySet().iterator();

row = sheet.createRow(i+1);

cell = row.createCell(0);

cell.setCellValue(i+1);

int index = 1;

while (iter.hasNext()) {

Map.Entry entry = (Map.Entry) iter.next();

//Object key = entry.getKey();

Object val = entry.getValue();

cell = row.createCell(index);

cell.setCellValue(val.toString());

index++;

}

}

}

ServletOutputStream sos = null;

try {

String fileName = name+".xls";

response.setContentType("application/vnk.ms-excel");

response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

response.setContentType("application/msexcel;charset=utf-8");

response.resetBuffer();

sos = response.getOutputStream();

wb.write(sos);

sos.flush();

} catch (IOException e) {

logger.error("导出excel工具类报错",e);

} finally {

try {

sos.close();

} catch (IOException e) {

logger.error("导出excel工具类报错",e);

}

}

}

public static List[] splitList(List list, Integer pageSize) {

if(pageSize == null){

pageSize = 300;

}

int total = list.size();

//总页数

int pageCount = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;

List[] result = new List[pageCount];

for(int i = 0; i < pageCount; i++) {

int start = i * pageSize;

//最后一条可能超出总数

int end = start + pageSize > total ? total : start + pageSize;

List subList = list.subList(start, end);

result[i] = subList;

}

return result;

}

常见问题

前台一定要使用表单的方式进行提交,ajax是不行的,因为ajax只能接受 xml、 json、html等类似字符串的返回,不能接受流作为返回值。否则程序不报错,就是不弹下载框。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值