如果数据量比较大(十万以上)建议导成多个excel文件,之后压缩成zip文件进行下载
- //生成一个excel文件
- WritableWorkbook wwb = null;
- try {
- //首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
- wwb = Workbook.createWorkbook(new File(fileName));
- } catch (IOException e) {
- log.error(e);
- }
- long totle = service.getTotle(searchParameters);//业务逻辑方法,获取总数,便于在excel分多个工作表
- //按65536条数据分页
- float res=Float.parseFloat(String.valueOf(totle));
- float mus=65536;
- float avg=res/mus;
- Map cols = (Map) request.getSession().getAttribute("columnsMap"); //业务逻辑方法
- for (int i = 0; i < avg+1; i++) {
- searchParameters.setEvent_id(String.valueOf(i*mus)); //分页查询条件
- searchParameters.setTotalLimit(String.valueOf((i+1)*mus));//分页查询条件
- List result = service.getEvents(searchParameters); //分页查询方法
- if(wwb!=null){
- //创建一个可写入的工作表
- //Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置
- WritableSheet ws = wwb.createSheet("列表"+(i+1), i);
- String colss = ((String) cols.get("cols")).substring("selected"
- .length() + 1);
- String[] columns = colss.split(","); //业务逻辑方法(添加标题)
- String[] colNames = ((String) cols.get("colNames")).split(",");
- for (int j = 0; j < columns.length; j++) {
- jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.BLACK);
- jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc);
- wcfFC.setBackground(Colour.GRAY_25);
- Label label = new Label(j, 0,colNames[j],wcfFC);
- ws.setColumnView(j, 20); //设置列宽
- ws.addCell(label); //添加标题
- }
- String str="";
- //下面开始添加单元格
- for(int m=0;m<result.size();m++){
- for(int j=0;j<columns.length;j++){
- Map map = (Map) result.get(m);
- //在表格中添加(业务数据)
- for (Object key : map.keySet()) {
- Object val = map.get(key);
- str=String.valueOf(val);
- //这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行
- Label labelC = new Label(j, m+1, str);
- //将生成的单元格添加到工作表中
- ws.addCell(labelC);
- }
- }
- }
- }
- }
- //Excel操作完毕之后,关闭所有的操作资源
- try {
- //从内存中写入文件中
- wwb.write();
- //关闭资源,释放内存
- wwb.close();
- } catch (IOException e) {
- log.error(e);
- } catch (WriteException e) {
- log.error(e);
- }
- //把生成的文件下载
- File file = new File(fileName);
- if(!file.exists()) throw new Exception("文件不存在!");
- FileInputStream fileInputStream = new FileInputStream(file);
- BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
- OutputStream outputStream = response.getOutputStream();
- BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
- response.setContentType("application/x-download");
- response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("事件列表.xls", "UTF-8"));
- int bytesRead = 0;
- byte[] buffer = new byte[8192];
- while ((bytesRead = bufferedInputStream.read(buffer, 0, 8192)) != -1) {
- bufferedOutputStream.write(buffer, 0, bytesRead);
- }
- bufferedOutputStream.flush();
- fileInputStream.close();
- bufferedInputStream.close();
- outputStream.close();
- bufferedOutputStream.close();