首页 > 代码库 > 用Java导出为excel表格
用Java导出为excel表格
导出的是最基础的excel表格,没有任何样式。
1 <input type="button" value="http://www.mamicode.com/输出到Excel" onclick=‘outputtable()‘ class="btn btn-info margin-right-20" style="width:80px;" /> 2 3 <script> 4 function outputtable(){ 5 url="outputAll.action"; 6 window.open(url); 7 8 } 9 </script>
在MVC的controller层中,写action
@RequestMapping("/outputEle.action") public String queEle(HttpServletRequest request, HttpServletResponse response, TableEle tableEle) throws Exception{ 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<String> list1 = null; Map<String,List> map = new HashMap<String, List>(); for (int i = 0; i < list.size(); i++) { list1 = new ArrayList<String>(); 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 <columnCount; 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 <columnCount; i++) { //遍历集合 HSSFCell cell = row.createCell(i); //将遍历到的写到单元格 sheet.autoSizeColumn(i); cell.setCellValue(list1.get(i)); } } } ByteArrayOutputStream os = new ByteArrayOutputStream(); workbook.write(os); byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(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 = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (final IOException e) { throw e; } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } return null; }
bizImpl层
//查找电量中的信息 @Override public List<TableEle> queEle(TableEle tableEle) { return eleMapper.queEle(tableEle); }
用Java导出为excel表格
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。