java导出为excel文件_用Java导出为excel表格

@RequestMapping("/outputEle.action")publicString queEle(HttpServletRequest request,

HttpServletResponse response, TableEle tableEle)throwsException{

request.setCharacterEncoding("utf-8");

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

String flag= "0";

HSSFWorkbook workbook= new HSSFWorkbook();//创建对象

int rowNum=1;

HSSFSheet sheet= workbook.createSheet("电量表"); //在Excel中建一个工作表,其名为默认值

String[] name={"时间","ID","负载电量","风能电量","光伏电量","电池电量"};//字段名,就是excel中的标题头

List list1 = null;

Map map = new HashMap();for (int i = 0; i < list.size(); i++) {

list1= new ArrayList();

list1.add(list.get(i).getTime());

list1.add(list.get(i).getID());

list1.add(list.get(i).getLoad_PH());

list1.add(list.get(i).getWind_PH());

list1.add(list.get(i).getSun_PH());

list1.add(list.get(i).getBattery_PH());

map.put(i+"", list1);

}int columnCount =name.length;

HSSFRow row1= sheet.createRow(0); //在索引0的位置创建行

for (short i = 0; i

sheet.autoSizeColumn(i);

String columnName=name[i];

HSSFCell cell1=row1.createCell(i);

cell1.setCellValue(columnName);

}if(columnCount>=1){for (int j = 0; j < map.size(); j++) {

HSSFRow row= sheet.createRow(j+1);

list1= map.get(j+"");for (short i = 0; i

HSSFCell cell = row.createCell(i); //将遍历到的写到单元格

sheet.autoSizeColumn(i);

cell.setCellValue(list1.get(i));

}

}

}

ByteArrayOutputStream os= newByteArrayOutputStream();

workbook.write(os);byte[] content =os.toByteArray();

InputStream is= newByteArrayInputStream(content);//设置response参数,可以打开下载页面

response.reset();

response.setContentType("application/vnd.ms-excel;charset=utf-8");

response.setHeader("Content-Disposition", "attachment;filename="+ new String(("电量表.xls").getBytes(), "iso-8859-1"));  //excel的表格名称

ServletOutputStream out=response.getOutputStream();

BufferedInputStream bis= null;

BufferedOutputStream bos= null;try{

bis= newBufferedInputStream(is);

bos= newBufferedOutputStream(out);byte[] buff = new byte[2048];intbytesRead;//Simple read/write loop.

while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {

bos.write(buff,0, bytesRead);

}

}catch (finalIOException e) {throwe;

}finally{if (bis != null)

bis.close();if (bos != null)

bos.close();

}return null;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值