精华内容
下载资源
问答
  • JAVA导出EXCEL并下载

    千次阅读 2015-10-16 13:56:09
    JAVA导出EXCEL并下载 一 ,流程大致如下 1.JSP页面点击按钮 2.点击导出excel按钮 3.点击确定按钮 (1)在谷歌浏览器中会直接下载 (2)在ie浏览器会提示保存路径 4.最后下载保存到本地,打开...

    JAVA导出EXCEL并下载

    一 ,流程大致如下

    1.JSP页面点击按钮


    2.点击导出excel按钮


    3.点击确定按钮

    (1)在谷歌浏览器中会直接下载


    (2)在ie浏览器会提示保存路径


    4.最后下载保存到本地,打开Excel表格,效果如下。


    二,下面来看具体代码

    前端js代码
    	function exportExcel() {
     		$.messager.confirm('确认', '确认把该搜索结果导出Excel表格 ?', function(r) {
    			if (r) {
    				var startTime = $('#startTime1').datetimebox('getValue');
    				var endTime = $('#endTime1').datetimebox('getValue');
    				var username = $("#username").val();
    				var mphone = $("#mphone").val();
    				var ordercode = $("#ordercode").val();
    				var orderStatus = $("#select_value").val();
    				$.messager.progress({
    					title : '处理中',
    					msg : '请稍后',
    				});
    				$.messager.progress('close');
    				location.href="${ctx}/tradingManage/exportExcel?startTime="+startTime+"&endTime="+endTime+"&username="+username+"&mphone="+mphone+"&ordercode="+ordercode+"&orderStatus="+orderStatus;
    			}
    		}); 
    	}

    java代码

    @ResponseBody
    	@RequestMapping(value="exportExcel")
    	public void exportExcel(HttpServletRequest request, HttpServletResponse resp) throws IOException
    	{
    		try
    		{
    			if (null == request || null == resp)
    			{
    				return;
    			}
    			List<VUserOrder> listContent = null;
    			String startTime = request.getParameter("startTime");
    			String endTime = request.getParameter("endTime");
    			String userName = request.getParameter("username");
    			String mphone = request.getParameter("mphone");
    			String orderCode = request.getParameter("ordercode");
    			String orderStatus = request.getParameter("orderStatus");
    			Map<String, Object> searchParams = new HashMap<String, Object>();
    			searchParams.put("LTE_type", OrderType.tx.getType());
    			searchParams.put("GTE_userId", 0);
    			if (null != startTime)
    				searchParams.put("GTE_createTime", DateUtils.getFormatDate(startTime, "yyyy-MM-dd HH:mm:ss"));
    			if (null != endTime)
    				searchParams.put("LTE_createTime", DateUtils.getFormatDate(endTime, "yyyy-MM-dd HH:mm:ss"));
    			if (null != userName)
    				searchParams.put("EQ_userName", userName);
    			if (null != mphone)
    				searchParams.put("EQ_userMphone", mphone);
    			if (null != orderCode)
    				searchParams.put("EQ_orderCode", orderCode);
    			if (null != orderStatus)
    				searchParams.put("EQ_status", orderStatus);
    			Specification<VUserOrder> spec = JpaQueryUtils.buildSpecification(VUserOrder.class, searchParams);
    			listContent = userOrderService.findAll(spec);
    			Map<Long, Map<String, String>> maps = authChsiService.getVUserOrderSchoolNameAndFacultyName(listContent);
    			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    			if (null != listContent)
    			{
    				int listContentSize = listContent.size();
    				for (int i = 0; i < listContentSize; i++)
    				{
    					if (null != listContent.get(i))
    					{
    						Map<String, String> map2 = maps.get(listContent.get(i).getId());
    						listContent.get(i).setJyrq(formatter.format((listContent.get(i).getUpdateTime())));
    						if (null != map2)
    						{
    							listContent.get(i).setSchoolName(map2.get("schoolName"));
    							listContent.get(i).setFacultyName(map2.get("facultyName"));
    						}
    					}
    				}
    			}
    			//生成Excel文件
    			userOrderService.exportExcel(request, resp, listContent);
    		}
    		catch (ServiceException e)
    		{
    			logger.info("=====导出excel异常====");
    		}
    		catch (Exception e1)
    		{
    			logger.info("=====导出excel异常====");
    		}
    	}

    上面的代码主要逻辑是查询出一个list对象,最后一步然后调用userOrderService中的exportExcel方法,可以直接忽视调用该方法前的查询代码,从controller直接调用以下方法。如下

    (而我的业务逻辑是根据搜索条件查询到相应的list,然后把管理员想导出的数据导出Excel)


    /**
    	 * excel导出交易记录
    	 * @param request
    	 * @param resp
    	 * @throws UnsupportedEncodingException
    	 */
    	public void exportExcel(HttpServletRequest request,HttpServletResponse resp,List<VUserOrder> listContent) throws UnsupportedEncodingException
    	{
    		HSSFWorkbook wb = new HSSFWorkbook();
    		request.setCharacterEncoding("UTF-8");
    		resp.setCharacterEncoding("UTF-8");
    		resp.setContentType("application/x-download");
    
    		String fileName = "交易记录.xls";
    		fileName = URLEncoder.encode(fileName, "UTF-8");
    		resp.addHeader("Content-Disposition", "attachment;filename=" + fileName);
    		HSSFSheet sheet = wb.createSheet("会员交易记录");
    		sheet.setDefaultRowHeight((short) (2 * 256));
    		sheet.setColumnWidth(0, 50 * 160);
    		HSSFFont font = wb.createFont();
    		font.setFontName("宋体");
    		font.setFontHeightInPoints((short) 16);
    		HSSFRow row = sheet.createRow((int) 0);
    		sheet.createRow((int) 1);
    		sheet.createRow((int) 2);
    		sheet.createRow((int) 3);
    		sheet.createRow((int) 4);
    		sheet.createRow((int) 5);
    		sheet.createRow((int) 6);
    		sheet.createRow((int) 7);
    		sheet.createRow((int) 8);
    		sheet.createRow((int) 9);
    		sheet.createRow((int) 10);
    		sheet.createRow((int) 11);
    		HSSFCellStyle style = wb.createCellStyle();
    		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    
    		HSSFCell cell = row.createCell(0);
    		cell.setCellValue("编号 ");
    		cell.setCellStyle(style);
    		cell = row.createCell(1);
    		cell.setCellValue("日期 ");
    		cell.setCellStyle(style);
    		cell = row.createCell(2);
    		cell.setCellStyle(style);
    		cell.setCellValue("订单号");
    		cell = row.createCell(3);
    		cell.setCellStyle(style);
    		cell.setCellValue("会员姓名");
    		cell = row.createCell(4);
    		cell.setCellStyle(style);
    		cell.setCellValue("会员手机号");
    		cell = row.createCell(5);
    		cell.setCellStyle(style);
    		cell.setCellValue("学校 ");
    		cell = row.createCell(6);
    		cell.setCellStyle(style);
    		cell.setCellValue("院系 ");
    		cell = row.createCell(7);
    		cell.setCellStyle(style);
    		cell.setCellValue("交易日期 ");
    		cell = row.createCell(8);
    		cell.setCellStyle(style);
    		cell.setCellValue("消费类型");
    		cell = row.createCell(9);
    		cell.setCellStyle(style);
    		cell.setCellValue("产品名称");
    		cell = row.createCell(10);
    		cell.setCellStyle(style);
    		cell.setCellValue("消费金额 ");
    		cell = row.createCell(11);
    		cell.setCellStyle(style);
    		cell.setCellValue("状态");
    
    		List<VUserOrder> vUserOrder = listContent;
    
    		for (int i = 0; i < vUserOrder.size(); i++)
    		{
    			HSSFRow row1 = sheet.createRow((int) i + 1);
    			VUserOrder vuserOrder = vUserOrder.get(i);
    			row1.createCell(0).setCellValue(i + 1);
    			row1.createCell(1).setCellValue(DateUtils.getFormatDateTime(vuserOrder.getCreateTime()));//日期
    			row1.createCell(2).setCellValue(vuserOrder.getOrderCode());//订单号
    			row1.createCell(3).setCellValue(vuserOrder.getUserName());//会员姓名
    			row1.createCell(4).setCellValue(vuserOrder.getUserMphone());//会员手机号
    			row1.createCell(5).setCellValue(vuserOrder.getSchoolName());//学校
    			row1.createCell(6).setCellValue(vuserOrder.getFacultyName());//院系
    			row1.createCell(7).setCellValue(vuserOrder.getJyrq());//交易日期
    			int orderType = vuserOrder.getType();
    			String type = "";
    			if (orderType == OrderType.xx.getType())
    			{
    				type = "线下消费";
    			}
    			else if (orderType == OrderType.df.getType())
    			{
    				type = "网购代付";
    			}
    			else if (orderType == OrderType.tx.getType())
    			{
    				type = "用户提现";
    			}
    			else if (orderType == OrderType.qe.getType())
    			{
    				type = "全额还款";
    			}
    			else if (orderType == OrderType.fq.getType())
    			{
    				type = "分期还款";
    			}
    			row1.createCell(8).setCellValue(type);//消费类型
    			row1.createCell(9).setCellValue(vuserOrder.getProductName());//产品名称
    			row1.createCell(10).setCellValue(vuserOrder.getAmount().doubleValue());//消费金额
    			row1.createCell(11).setCellValue(
    					(vuserOrder.getStatus() == 1) ? "交易成功" : (vuserOrder.getStatus() == 2) ? "失败" : "处理中");//状态
    		}
    		try
    		{
    			OutputStream out = resp.getOutputStream();
    			wb.write(out);
    			out.close();
    		}
    		catch (ServiceException e)
    		{
    			logger.info("=====导出excel异常====");
    		}
    		catch (Exception e1)
    		{
    			logger.info("=====导出excel异常====");
    		}
    	}

    所以代码结束。调用该方法直接传进list对象,剩下的自己稍微修改下list的属性就可以ok了。

    需要注意的是这里的jsp中用 location.href 发送到controller。如果有不明白的可以一起交流。大笑

    展开全文
  • Java导出Excel并下载

    2019-12-25 11:48:42
    Java使用POI生成Excel下载文件 Java查询结果生成多 Sheet 的页 Excel,提供页面导出功能 查询结果直接导出 Excel 思路: 使用 import javax.servlet.http.HttpServletResponse 获取输出流,将文件写入,实现导出 ...

    Java使用POI生成Excel、下载文件

    Java查询结果生成多 Sheet 的页 Excel,提供页面导出功能

    查询结果直接导出 Excel

    • 思路: 使用 import javax.servlet.http.HttpServletResponse 获取输出流,将文件写入,实现导出

    controller 代码

      @RequestMapping(value = "xx" method = RequestMethod.POST)
      public void batchCommonalityQuery(HttpServletResponse response) {
        try {
          String fileName = file.getOriginalFilename();
          // 文件名称   
          String name = "xx.xlsx";
    
          response.setContentType("application/octet-stream");
          response.addHeader("Content-Disposition",	"attachment;filename=\"" + new String(name.getBytes("UTF-8"), "ISO-8859-1"));
          
          OutputStream outputStream = response.getOutputStream();
          
          List<List<UserUrlVO>> list = this.commonalityService.batchCommonsQuery(file, outputStream);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

    service 代码

      private void exportExcel(List<List<T>> list, List<String> sheetName, String[] header, OutputStream out) {
        HSSFWorkbook workbook = new HSSFWorkbook();
    
        try {
          for (int i = 0; i < list.size(); i++) {
            // sheet页名
            HSSFSheet sheet = workbook.createSheet(sheetName.get(i));
    
            // list内容
            List<T> values = list.get(i);
            HSSFRow row;// = sheet.createRow(values.size());
    
            // 设置行标题(Excel第一行)
            row = sheet.createRow(0);
            for (int h = 0; h < header.length; h++) {
              row.createCell(h).setCellValue(header[h]);
              sheet.autoSizeColumn(h, true);
              sheet.setColumnWidth(h, sheet.getColumnWidth(h) * 17 / 10);
            }
            // 写入行 —— 单元格
            for (int j = 0; j < values.size(); j++) {
              row = sheet.createRow(j + 1);
    
              Object object = values.get(j);
              // 遍历实体类属性
              Field[] fields = object.getClass().getDeclaredFields();
              // 单元格内容
              for (int k = 0; k < fields.length; k++) {
                Field field = fields[k];
                field.setAccessible(true);
                row.createCell(k).setCellValue(field.get(object).toString());
              }
            }
          }
          // 响应下载
          workbook.write(out);
          out.close();
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          try {
            out.flush();
            out.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }

    将文件保存到服务器,提供返回下载路径

    controller 代码

      @RequestMapping(value = "downloadFile")
    	public void downloadFile(@RequestParam(value = "filepath", required = true) String filePath,HttpServletResponse response) {
    		this.commonalityService.downloadFile(filePath, response);
    	}

    service 代码

    1. 将文件写入本地
    final static String EXCEL_PATH = System.getProperty("os.name").toLowerCase().startsWith("win") ? "D:\\fileupload\\excel\\" : "/root/commonality";
    
      // 将文件写入本地
      private void writeExcel(List<List<T>> list, List<String> sheetName, String[] header, String fileName) {
        HSSFWorkbook workbook = new HSSFWorkbook();
    
        try {
          for (int i = 0; i < list.size(); i++) {
            // sheet页名
            HSSFSheet sheet = workbook.createSheet(sheetName.get(i));
    
            // list内容
            List<T> values = list.get(i);
            HSSFRow row;// = sheet.createRow(values.size());
    
            // 设置行标题(Excel第一行)
            row = sheet.createRow(0);
            for (int h = 0; h < header.length; h++) {
              row.createCell(h).setCellValue(header[h]);
              sheet.autoSizeColumn(h, true);
              sheet.setColumnWidth(h, sheet.getColumnWidth(h) * 17 / 10);
            }
            // 写入行 —— 单元格
            for (int j = 0; j < values.size(); j++) {
              row = sheet.createRow(j + 1);
    
              Object object = values.get(j);
              // 遍历实体类属性
              Field[] fields = object.getClass().getDeclaredFields();
              // 单元格内容
              for (int k = 0; k < fields.length; k++) {
                Field field = fields[k];
                field.setAccessible(true);
                row.createCell(k).setCellValue(field.get(object).toString());
              }
            }
          }
          // 判断文件夹目录是否存在,不存在则创建
          File file = new File(EXCEL_PATH);
          if (!file.exists()) {
            // 创建的是多级目录,file.mkdir(); 只能创建一级目录
            file.mkdirs();
          }
          // 生成文件保存到服务器
          String path = EXCEL_PATH + fileName;
          FileOutputStream stream = new FileOutputStream(path);
          workbook.write(stream);
          stream.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    1. 下载文件
    	public void downloadFile(String filePath, HttpServletResponse response) {
    		OutputStream outputStream = null;
    		FileInputStream fis = null;
    		try {
    			response.setContentType("application/octet-stream");
    			response.setCharacterEncoding("UTF-8");
    			response.addHeader("Content-Disposition",
    					"attachment;filename=\"" + new String(filePath.getBytes("UTF-8"), "ISO-8859-1"));
    
    			outputStream = response.getOutputStream();
    			fis = new FileInputStream(EXCEL_PATH + filePath);
    			byte[] bytes = new byte[1024];
    			int lengtth = 0;
    			while ((lengtth = fis.read(bytes)) != -1) {
    				outputStream.write(bytes, 0, lengtth);
    			}
    			outputStream.flush();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				if (outputStream != null) {
    					outputStream.close();
    				}
    				if (fis != null) {
    					fis.close();
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    
    		}
    	}

    公共方法

      // @描述:是否是2003的excel,返回true是2003
      private boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
      }
    
      // @描述:是否是2007的excel,返回true是2007
      private boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
      }
    
      private Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
          switch (cell.getCellType()) {
          case Cell.CELL_TYPE_NUMERIC:
            cellValue = NumberToTextConverter.toText(cell.getNumericCellValue());
            break;
          case Cell.CELL_TYPE_STRING:
            cellValue = cell.getRichStringCellValue().getString().trim();
            break;
          default:
            cellValue = "";
            break;
          }
        } else {
          cellValue = "";
        }
        return cellValue;
      }
    展开全文
  • java导出excel并下载

    2017-03-23 14:17:13
    mybatis中导出excel并下载 工具类: public class ExportExcel { public void exportExcel(Collection dataset, OutputStream out) { exportExcel("测试POI导出EXCEL文档", null, dataset, out, "yyyy-MM-dd"); ...

    mybatis中导出excel并下载

    工具类:

    public class ExportExcel<T> {
    public void exportExcel(Collection<T> dataset, OutputStream out) {
    exportExcel("测试POI导出EXCEL文档", null, dataset, out, "yyyy-MM-dd");
    }


    public void exportExcel(String[] headers, Collection<T> dataset, OutputStream out) {
    exportExcel("测试POI导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd");
    }


    public void exportExcel(String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
    exportExcel("测试POI导出EXCEL文档", headers, dataset, out, pattern);
    }


    @SuppressWarnings("unchecked")
    public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
    // 声明一个工作薄
    HSSFWorkbook workbook = new HSSFWorkbook();
    // 生成一个表格
    HSSFSheet sheet = workbook.createSheet(title);
    // 设置表格默认列宽度为15个字节
    sheet.setDefaultColumnWidth((short) 15);
    // 生成一个样式
    HSSFCellStyle style = workbook.createCellStyle();
    // 设置这些样式
    style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    style.setBorderTop(HSSFCellStyle.BORDER_THIN);
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    // 生成一个字体
    HSSFFont font = workbook.createFont();
    font.setColor(HSSFColor.VIOLET.index);
    font.setFontHeightInPoints((short) 12);
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    // 把字体应用到当前的样式
    style.setFont(font);
    // 生成并设置另一个样式
    HSSFCellStyle style2 = workbook.createCellStyle();
    style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
    style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
    style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
    style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    // 生成另一个字体
    HSSFFont font2 = workbook.createFont();
    font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
    // 把字体应用到当前的样式
    style2.setFont(font2);


    // 声明一个画图的顶级管理器
    HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
    // 定义注释的大小和位置,详见文档
    HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
    // 设置注释内容
    comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
    // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
    comment.setAuthor("leno");


    // 产生表格标题行
    HSSFRow row = sheet.createRow(0);
    for (short i = 0; i < headers.length; i++) {
    HSSFCell cell = row.createCell(i);
    cell.setCellStyle(style);
    HSSFRichTextString text = new HSSFRichTextString(headers[i]);
    cell.setCellValue(text);
    }


    // 遍历集合数据,产生数据行
    Iterator<T> it = dataset.iterator();
    int index = 0;
    while (it.hasNext()) {
    index++;
    row = sheet.createRow(index);
    T t = (T) it.next();
    // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
    Field[] fields = t.getClass().getDeclaredFields();
    for (short i = 0; i < fields.length; i++) {
    HSSFCell cell = row.createCell(i);
    cell.setCellStyle(style2);
    Field field = fields[i];
    String fieldName = field.getName();
    String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    try {
    Class tCls = t.getClass();
    Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
    Object value = getMethod.invoke(t, new Object[] {});
    // 判断值的类型后进行强制类型转换
    String textValue = null;
    // if (value instanceof Integer) {
    // int intValue = (Integer) value;
    // cell.setCellValue(intValue);
    // } else if (value instanceof Float) {
    // float fValue = (Float) value;
    // textValue = new HSSFRichTextString(
    // String.valueOf(fValue));
    // cell.setCellValue(textValue);
    // } else if (value instanceof Double) {
    // double dValue = (Double) value;
    // textValue = new HSSFRichTextString(
    // String.valueOf(dValue));
    // cell.setCellValue(textValue);
    // } else if (value instanceof Long) {
    // long longValue = (Long) value;
    // cell.setCellValue(longValue);
    // }
    if (value instanceof Boolean) {
    boolean bValue = (Boolean) value;
    textValue = "男";
    if (!bValue) {
    textValue = "女";
    }
    } else if (value instanceof Date) {
    Date date = (Date) value;
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    textValue = sdf.format(date);
    } else if (value instanceof byte[]) {
    // 有图片时,设置行高为60px;
    row.setHeightInPoints(60);
    // 设置图片所在列宽度为80px,注意这里单位的一个换算
    sheet.setColumnWidth(i, (short) (35.7 * 80));
    // sheet.autoSizeColumn(i);
    byte[] bsValue = (byte[]) value;
    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6,
    index);
    anchor.setAnchorType(2);
    patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
    } else {
    // 其它数据类型都当作字符串简单处理
    textValue = value.toString();
    }
    // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
    if (textValue != null) {
    Pattern p = Pattern.compile("^//d+(//.//d+)?$");
    Matcher matcher = p.matcher(textValue);
    if (matcher.matches()) {
    // 是数字当作double处理
    cell.setCellValue(Double.parseDouble(textValue));
    } else {
    HSSFRichTextString richString = new HSSFRichTextString(textValue);
    HSSFFont font3 = workbook.createFont();
    font3.setColor(HSSFColor.BLUE.index);
    richString.applyFont(font3);
    cell.setCellValue(richString);
    }
    }
    } catch (SecurityException e) {
    e.printStackTrace();
    } catch (NoSuchMethodException e) {
    e.printStackTrace();
    } catch (IllegalArgumentException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    } catch (InvocationTargetException e) {
    e.printStackTrace();
    } finally {
    // 清理资源
    }
    }
    }
    try {
    workbook.write(out);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }


    controller中

    public String createExcel(HttpServletResponse response) throws Exception {
    ExportExcel<Test> ex = new ExportExcel<Test>();
    String[] helder = { "数据信息", "序号", "用户昵称", "用户年龄", "照片名称", "用户照片" };
    List<Test> tl = sysTestService.queryAllList();
    OutputStream out = new FileOutputStream("E://userMessage.xls");
    ex.exportExcel(helder, tl, out);
    out.close();
    // path是指欲下载的文件的路径。
    String path = "E://userMessage.xls";
    File file = new File(path);
    // 取得文件名。
    String filename = file.getName();
    // 以流的形式下载文件。
    InputStream fis = new BufferedInputStream(new FileInputStream(path));
    byte[] buffer = new byte[fis.available()];
    fis.read(buffer);
    fis.close();
    // 清空response
    response.reset();
    // 设置response的Header
    response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
    response.addHeader("Content-Length", "" + file.length());
    OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    toClient.write(buffer);
    toClient.flush();
    toClient.close();
    file.delete();
    return "redirect:/toproad/test.do";
    }

    展开全文
  • 我们使用的导出并下载功能是利用一个插件叫POI的插件提供的导出功能,很实用;首先先导入Jar包:Action代码:public void exportToExcel(List data) throws Exception{this.setEnableAccessRequest(true);this....

    我们使用的导出并下载功能是利用一个插件叫POI的插件提供的导出功能,很实用;首先先导入Jar包:

    812e91d6b1bafb2824f049eda1dadfbe.png

    Action代码:

    public void exportToExcel(List data) throws Exception

    {

    this.setEnableAccessRequest(true);

    this.setEnableAccessResponse(true);

    HttpServletRequest request = this.getRequest();

    HttpServletResponse response = this.getResponse();

    String randomNumber = request.getParameter("randomNumber");// session名称

    try {

    session = request.getSession();

    session.setAttribute(randomNumber, new Double(1));

    // 导出的EXCEL文件名

    String exportFileName = "addressBook.xlsx";

    response.reset();

    response.setContentType("octets/stream");

    // response.setHeader("Content-Disposition","attachment;filename="+exportFileName);

    response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(exportFileName.getBytes("UTF-8"), "iso8859-1") + "\"");

    // 导出的EXCEL列属性

    List columnListName = new ArrayList();

    columnListName.add("userName&姓名");

    columnListName.add("mobile&手机");

    columnListName.add("shopTel&分店电话");

    columnListName.add("postName&职位");

    columnListName.add("email&邮箱");

    columnListName.add("shopAddress&分店地址");

    Bean2ExcelConversionUtils.beans2excelFile07(columnListName, data, response.getOutputStream());

    session.setAttribute(randomNumber, new Double(100));

    } catch (Exception e) {

    e.printStackTrace();

    session.setAttribute(randomNumber, new Double(100));

    } catch (Throwable e) {

    e.printStackTrace();

    session.setAttribute(randomNumber, new Double(100));

    }

    }

    JSP代码:

    function exportToExcel() {

    var randomNumber=new Date().getTime();

    top.$.jBox.tip("正在导出...", 'loading');

    var exportDate = "${ctx}/xxxAction.do?method=export&randomNumber="+randomNumber;

    $("#exportForm").attr("action", exportDate);

    $("#exportForm").attr("method","post");

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

    }

    因为是使用的插件,所以需要引入一个工具类(下面的工具类直接复制到新建的类文件里面即可)

    import java.beans.Introspector;

    import java.beans.PropertyDescriptor;

    import java.io.File;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.io.OutputStream;

    import java.text.SimpleDateFormat;

    import java.util.ArrayList;

    import java.util.Date;

    import java.util.HashMap;

    import java.util.List;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

    import org.apache.poi.hssf.usermodel.HSSFCell;

    import org.apache.poi.hssf.usermodel.HSSFRow;

    import org.apache.poi.hssf.usermodel.HSSFSheet;

    import org.apache.poi.hssf.usermodel.HSSFWorkbook;

    import org.apache.poi.ss.usermodel.Cell;

    import org.apache.poi.ss.usermodel.CellStyle;

    import org.apache.poi.ss.usermodel.Row;

    import org.apache.poi.ss.usermodel.Sheet;

    import org.apache.poi.ss.usermodel.Workbook;

    import org.apache.poi.xssf.streaming.SXSSFSheet;

    import org.apache.poi.xssf.streaming.SXSSFWorkbook;

    /**

    * @author Tan Jiangyong

    * @date 2013-9-3 下午3:36:43

    * @version V1.0

    */

    @SuppressWarnings("all")

    public class Bean2ExcelConversionUtils {

    private static final String PATTERN="yyyy-MM-dd HH:mm:ss"; //excel日期格式,默认配置

    private static final String DATE_PATTERN="yyyy-MM-dd"; //excel日期格式

    private static final String DATE_HH_PATTERN="HH:mm:ss"; //excel时间格式

    private static final int TOTAL_SIZE=40000; //每个excel写入多少数据(默认配置)

    private static final int MAX_SHEET_SIZE=10000; //每一个sheet的大小(默认配置)

    private static final int COLUMN_WIDTH_WORD=25; //列宽,默认汉字个数为25个

    private static final int FLUSH_ROWS=100; //每生成excel行数,内存中缓存记录数清空(目的,避免零时文件过大)

    /**

    * 07、10办公版EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据)

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param result 数字字典Map集

    * @param filePath 服务器存放文件路径

    * @param fileName 文件名称

    * @param totalSize EXCEL条数量

    * @param maxSheetSize sheet页条数量

    * @return 文件集合

    * @throws Exception

    */

    public static List beans2excelFile07(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{

    if(totalSize==null || totalSize<=0)

    totalSize=TOTAL_SIZE;

    if(maxSheetSize==null || maxSheetSize<=0)

    maxSheetSize=MAX_SHEET_SIZE;

    if(fileName==null)

    fileName="";

    return beans2excelFile2007(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);

    }

    /**

    * 07、10办公版EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据)

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param result 数字字典Map集

    * @param filePath 服务器存放文件路径

    * @param fileName 文件名称

    * @param totalSize EXCEL条数量

    * @param maxSheetSize sheet页条数量

    * @param request 客户端请求对象

    * @param response 客户端响应对象

    * @throws Exception

    */

    public static void beans2excelFile07(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize,HttpServletRequest request,HttpServletResponse response) throws Exception{

    if(totalSize==null || totalSize<=0)

    totalSize=TOTAL_SIZE;

    if(maxSheetSize==null || maxSheetSize<=0)

    maxSheetSize=MAX_SHEET_SIZE;

    if(fileName==null)

    fileName="";

    List files = beans2excelFile2007(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);

    DownLoadUtils.downLoadFiles(files, filePath, request, response);

    }

    /**

    * 07、10办公版EXCEL导出,每个EXCEL组织数据

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param result 数字字典Map集

    * @param filePath 服务器存放文件路径

    * @param fileName 文件名称

    * @param totalSize EXCEL条数量

    * @param maxSheetSize sheet页条数量

    * @return 文件集合

    * @throws Exception

    */

    private static List beans2excelFile2007(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{

    if ((listName == null) || (listName.size() == 0)) {

    throw new Exception("listName is null when create excel document");

    }

    List listFile=new ArrayList();//返回的文件集合

    int size=beans==null?0:beans.size();

    String fileSuffixName=".xlsx";//后缀

    String path="";//文件路径

    Integer startIdx=0;//数据读取的起始行

    Integer endIdx=0;//数据读取的结束行

    (new File(filePath)).mkdirs(); //没有该目录创建目录

    if(size==0){

    startIdx=0;

    endIdx=(totalSize)>size?size:(totalSize);

    String name=fileName+"_第0-0条数据";

    path=filePath+File.separatorChar+name+fileSuffixName;

    Workbook wb =new SXSSFWorkbook();

    buildExcelDocument2007(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);

    //没有文件,创建文件

    File file = new File(path);

    if (!file.exists()){

    file.createNewFile();

    }

    FileOutputStream out=new FileOutputStream(file);

    wb.write(out);

    out.close();

    return listFile;

    }

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

    int remainder=i%totalSize;

    if(size==0 || remainder==0){

    startIdx=i;

    endIdx=(i+totalSize)>size?size:(i+totalSize);

    String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据";

    path=filePath+"/"+name+fileSuffixName;

    Workbook wb =new SXSSFWorkbook();

    buildExcelDocument2007(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);

    //没有文件,创建文件

    File file = new File(path);

    if (!file.exists()){

    file.createNewFile();

    }

    FileOutputStream out=new FileOutputStream(file);

    wb.write(out);

    out.close();

    listFile.add(file);

    }else if((size-i)endIdx){//最后,不满一万条

    startIdx=i;

    endIdx=i+totalSize;

    String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据";

    path=filePath+name+"."+fileSuffixName;//没有文件,创建文件

    Workbook wb =new SXSSFWorkbook();

    buildExcelDocument2007(wb, listName, beans, result,startIdx,endIdx,maxSheetSize);

    //没有文件,创建文件

    File file = new File(path);

    if (!file.exists()){

    file.createNewFile();

    }

    FileOutputStream out=new FileOutputStream(file);

    wb.write(out);

    out.close();

    listFile.add(file);

    }

    }

    return listFile;

    }

    /**

    * 07、10办公版EXCEL导出,每个EXCEL写入数据

    * @param wb EXCEL工作薄

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param result 数字字典Map集

    * @param startIdx 数据集合,开始行

    * @param endIdx 数据集合,结束始行

    * @param maxSheetSize SHEET页条数

    * @throws Exception

    */

    private static void buildExcelDocument2007(Workbook wb, List listName, List beans,HashMap> result,Integer startIdx,Integer endIdx,Integer maxSheetSize) throws Exception

    {

    int totalSize=endIdx-startIdx;//总共条数

    try

    {

    CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);

    List titles = new ArrayList();

    List beanAttrNames = new ArrayList();

    boolean flagListExists=false;

    List flagList=new ArrayList();

    List widthList=new ArrayList();

    HashMap dateMap=new HashMap();

    String[] header = new String[listName.size()];

    int rows_max = 0;//标题占多少列

    for (int i=0;i

    {

    String[] str=listName.get(i).split("&");

    String en_name=str[0];

    String zh_name=str[1];

    beanAttrNames.add(i,en_name);

    titles.add(i, zh_name);

    header[i]=zh_name;

    if (zh_name.split("_").length > rows_max) {

    rows_max = zh_name.split("_").length;

    }

    if(str.length>2){

    String flag=str[2];

    flagList.add(i,flag);

    if(!flagListExists)

    flagListExists=true;

    }

    if(str.length>3){

    widthList.add(str[3]);

    }

    if(str.length>4){

    dateMap.put(en_name, str[4]);

    }

    }

    PropertyDescriptor[] props = null;

    int size=endIdx-startIdx;

    Sheet sheet=null;

    //如果没有数据,导出表头

    if(size==0){

    sheet=ExcelHeadUtils.getExcelHead2007(wb, header, "Sheet1");

    sheet.setDefaultRowHeight((short)350);//高度

    setColumnWidth2007(widthList, sheet,beanAttrNames.size());

    return ;

    }

    int u=1;//用来创建每个sheet的行

    int h=0;//用来标注每个sheet也得名字:多少行-多少行

    for (int i = startIdx; i < endIdx ; i++) {

    int remainder=h%maxSheetSize;

    if(size==0 || i==startIdx || remainder==0){

    u=1;

    int section=(h+maxSheetSize)>totalSize?totalSize:(h+maxSheetSize);

    sheet=ExcelHeadUtils.getExcelHead2007(wb, header,"第"+(h+1)+"-"+section+"条");

    sheet.createFreezePane( 1, rows_max, 1, rows_max);

    sheet.setDefaultRowHeight((short)350);//高度

    setColumnWidth2007(widthList, sheet,beanAttrNames.size());

    }

    if(props==null)

    props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();

    Object bean = beans.get(i);

    Row row = sheet.createRow(u+rows_max-1);

    u++;

    h++;

    for (int j = 0; j < beanAttrNames.size(); j++) {

    String beanAttrName = (String)beanAttrNames.get(j);

    String flag="";

    if(flagListExists)

    flag=(String)flagList.get(j);

    for (int k = 0; k < props.length; k++) {

    String propName = props[k].getName();

    if (propName.equals(beanAttrName))

    {

    String pattern=dateMap.get(beanAttrName);

    Cell cell = row.createCell((short)j);

    Object cellValue = callGetter(bean, props[k],pattern);

    if("true".equalsIgnoreCase(flag)){

    if(result!=null){

    HashMap hash=result.get(beanAttrName);

    if(hash!=null)

    cellValue=hash.get(cellValue);

    }

    }

    if (cellValue == null) {

    cellValue = "";

    }

    setExcelCellText2007(cell, cellValue.toString(),cellStyle);

    }

    }

    }

    //每当行数达到设置的值就刷新数据到硬盘,以清理内存

    if(i%FLUSH_ROWS==0){

    ((SXSSFSheet)sheet).flushRows();

    }

    }

    } catch (Exception e) {

    throw new Exception(e);

    }

    }

    /**

    * 07、10办公版EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个)

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param maxSheetSize SHEET页的条数

    * @param outputStream 客户端输出流

    * @throws Exception

    */

    public static void beans2excelFile07(List listName,List beans, OutputStream outputStream) throws Exception{

    if ((listName == null) || (listName.size() == 0)) {

    throw new Exception("listName is null when create excel document");

    }

    if (outputStream == null) {

    throw new Exception("outputStream is null when create excel document");

    }

    Workbook wb =new SXSSFWorkbook();

    beans2excelFile07(listName, beans, null, null, MAX_SHEET_SIZE, outputStream);

    try {

    wb.write(outputStream);

    outputStream.close();

    } catch (IOException e) {

    throw new Exception(e);

    }

    }

    /**

    * 07、10办公版EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个)

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param maxSheetSize SHEET页的条数

    * @param outputStream 客户端输出流

    * @throws Exception

    */

    public static void beans2excelFile07(List listName,List beans,HashMap> result,String sheetName,Integer maxSheetSize, OutputStream outputStream) throws Exception{

    if ((listName == null) || (listName.size() == 0)) {

    throw new Exception("listName is null when create excel document");

    }

    if (outputStream == null) {

    throw new Exception("outputStream is null when create excel document");

    }

    if(maxSheetSize==null || maxSheetSize<=0){

    maxSheetSize=MAX_SHEET_SIZE;

    }

    if(sheetName==null || "".equals(sheetName.trim())){

    sheetName="Sheet";

    }

    Workbook wb =new SXSSFWorkbook();

    if(maxSheetSize==null || maxSheetSize<=0){

    maxSheetSize=MAX_SHEET_SIZE;

    }

    buildExcelDocument2007(wb, listName, beans,result,sheetName,maxSheetSize);

    try {

    wb.write(outputStream);

    outputStream.close();

    } catch (IOException e) {

    throw new Exception(e);

    }

    }

    /**

    *

    * @param listName

    * @param beans

    * @param response

    * @param fileName 导出的文件名称

    * @throws Exception

    */

    public static void beans2excelFile07(List listName, List beans, HttpServletResponse response,String fileName) throws Exception {

    response.reset();

    response.setContentType("octets/stream");

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

    if ((listName == null) || (listName.size() == 0)) {

    throw new Exception("listName is null when create excel document");

    }

    if (response.getOutputStream() == null) {

    throw new Exception("outputStream is null when create excel document");

    }

    beans2excelFile07(listName, beans, null, null, MAX_SHEET_SIZE, response.getOutputStream());

    }

    /**

    * 07、10办公版EXCEL导出,EXCEL写入数据

    * @param wb EXCEL工作薄

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param maxSheetSize SHEET页的条数

    * @throws Exception

    */

    private static void buildExcelDocument2007(Workbook wb, List listName, List beans,HashMap> result,String sheetName,Integer maxSheetSize) throws Exception

    {

    try

    {

    CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);

    List titles = new ArrayList();

    List beanAttrNames = new ArrayList();

    List widthList = new ArrayList();

    HashMap dateMap=new HashMap();

    String[] header = new String[listName.size()];

    int rows_max = 0;//标题占多少列

    List flagList=new ArrayList();

    boolean flagListExists=false;

    for (int i=0;i

    {

    String[] str=listName.get(i).split("&");

    String en_name=str[0];

    String zh_name=str[1];

    beanAttrNames.add(i,en_name);

    titles.add(i, zh_name);

    header[i]=zh_name;

    if (zh_name.split("_").length > rows_max) {

    rows_max = zh_name.split("_").length;

    }

    if(str.length>2){

    String flag=str[2];

    flagList.add(i,flag);

    if(!flagListExists)

    flagListExists=true;

    }

    if(str.length>3){

    widthList.add(str[3]);

    }

    if(str.length>4){

    dateMap.put(en_name, str[4]);

    }

    }

    PropertyDescriptor[] props = null;

    int size=beans==null?0:beans.size();

    Sheet sheet=null;

    //如果没有数据,导出表头

    if(size==0){

    sheet=ExcelHeadUtils.getExcelHead2007(wb, header, sheetName);

    sheet.setDefaultRowHeight((short)350);//高度

    setColumnWidth2007(widthList, sheet,beanAttrNames.size());

    return ;

    }

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

    int remainder=i%maxSheetSize;

    if(size==0 || i==0 || remainder==0){

    sheet=ExcelHeadUtils.getExcelHead2007(wb, header,sheetName+(i/maxSheetSize));

    sheet.createFreezePane( 1, rows_max, 1, rows_max);

    sheet.setDefaultRowHeight((short)350);//高度

    setColumnWidth2007(widthList, sheet,beanAttrNames.size());

    }

    if(props==null)

    props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();

    Object bean = beans.get(i);

    Row row = sheet.createRow(remainder+rows_max);

    for (int j = 0; j < beanAttrNames.size(); j++) {

    String beanAttrName = (String)beanAttrNames.get(j);

    String flag="";

    if(flagListExists)

    flag=(String)flagList.get(j);

    for (int k = 0; k < props.length; k++) {

    String propName = props[k].getName();

    if (propName.equals(beanAttrName))

    {

    String pattern=dateMap.get(beanAttrName);

    Cell cell = row.createCell((short)j);

    Object cellValue = callGetter(bean, props[k],pattern);

    if("true".equalsIgnoreCase(flag)){

    if(result!=null){

    HashMap hash=result.get(beanAttrName);

    if(hash!=null)

    cellValue=hash.get(cellValue);

    }

    }

    if (cellValue == null) {

    cellValue = "";

    }

    setExcelCellText2007(cell, cellValue.toString(),cellStyle);

    }

    }

    }

    //每当行数达到设置的值就刷新数据到硬盘,以清理内存

    if(i%FLUSH_ROWS==0){

    ((SXSSFSheet)sheet).flushRows();

    }

    }

    } catch (Exception e) {

    throw new Exception(e);

    }

    }

    /**

    * 07、10办公版EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个)

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param maxSheetSize SHEET页的条数

    * @param outputStream 客户端输出流

    * @throws Exception

    */

    public static void beans2excelFile07List(List> listColumnName,List list2beans,HashMap>> result,List listSheetName, OutputStream outputStream) throws Exception{

    if ((listColumnName == null) || (listColumnName.size() == 0)) {

    throw new Exception("listColumnName is null when create excel document");

    }

    if (list2beans.size() != listColumnName.size()) {

    throw new Exception("list2beans and listColumnName size Unequal");

    }

    if (outputStream == null) {

    throw new Exception("outputStream is null when create excel document");

    }

    Workbook wb =new SXSSFWorkbook();

    buildExcelDocument2007List(wb, listColumnName, list2beans, result, listSheetName);

    try {

    wb.write(outputStream);

    outputStream.close();

    } catch (IOException e) {

    throw new Exception(e);

    }

    }

    /**

    * 07、10办公版EXCEL导出,EXCEL写入数据

    * @param wb EXCEL工作薄

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param maxSheetSize SHEET页的条数

    * @throws Exception

    */

    private static void buildExcelDocument2007List(Workbook wb, List> listColumnName,List list2beans,HashMap>> resultMap,List listSheetName) throws Exception

    {

    try

    {

    int sheets=listColumnName.size();

    boolean sheetNameIsNullFlag=false;

    if(listSheetName==null || listSheetName.size()!=sheets){

    sheetNameIsNullFlag=true;

    }

    for (int s = 0; s < sheets; s++) {

    String sheetName="Sheet"+s;

    if(!sheetNameIsNullFlag){

    sheetName=listSheetName.get(s);

    }

    List listName=listColumnName.get(s);

    CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);

    List titles = new ArrayList();

    List beanAttrNames = new ArrayList();

    List widthList = new ArrayList();

    HashMap dateMap=new HashMap();

    String[] header = new String[listName.size()];

    int rows_max = 0;//标题占多少列

    List flagList=new ArrayList();

    boolean flagListExists=false;

    for (int i=0;i

    {

    String[] str=listName.get(i).split("&");

    String en_name=str[0];

    String zh_name=str[1];

    beanAttrNames.add(i,en_name);

    titles.add(i, zh_name);

    header[i]=zh_name;

    if (zh_name.split("_").length > rows_max) {

    rows_max = zh_name.split("_").length;

    }

    if(str.length>2){

    String flag=str[2];

    flagList.add(i,flag);

    if(!flagListExists)

    flagListExists=true;

    }

    if(str.length>3){

    widthList.add(str[3]);

    }

    if(str.length>4){

    dateMap.put(en_name, str[4]);

    }

    }

    PropertyDescriptor[] props = null;

    ArrayList beans=(ArrayList)list2beans.get(s);

    int size=beans==null?0:beans.size();

    Sheet sheet=null;

    //如果没有数据,导出表头

    if(size==0){

    sheet=ExcelHeadUtils.getExcelHead2007(wb, header, sheetName);

    sheet.setDefaultRowHeight((short)350);//高度

    setColumnWidth2007(widthList, sheet,beanAttrNames.size());

    return ;

    }

    HashMap> result=null;

    if(resultMap!=null){

    result=resultMap.get(sheetName);

    }

    sheet=ExcelHeadUtils.getExcelHead2007(wb, header,sheetName);

    sheet.createFreezePane( 1, rows_max, 1, rows_max);

    sheet.setDefaultRowHeight((short)350);//高度

    setColumnWidth2007(widthList, sheet,beanAttrNames.size());

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

    if(props==null)

    props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();

    Object bean = beans.get(i);

    Row row = sheet.createRow(rows_max+i);

    for (int j = 0; j < beanAttrNames.size(); j++) {

    String beanAttrName = (String)beanAttrNames.get(j);

    String flag="";

    if(flagListExists)

    flag=(String)flagList.get(j);

    for (int k = 0; k < props.length; k++) {

    String propName = props[k].getName();

    if (propName.equals(beanAttrName))

    {

    String pattern=dateMap.get(beanAttrName);

    Cell cell = row.createCell((short)j);

    Object cellValue = callGetter(bean, props[k],pattern);

    if("true".equalsIgnoreCase(flag)){

    if(result!=null){

    HashMap hash=result.get(beanAttrName);

    if(hash!=null)

    cellValue=hash.get(cellValue);

    }

    }

    if (cellValue == null) {

    cellValue = "";

    }

    setExcelCellText2007(cell, cellValue.toString(),cellStyle);

    }

    }

    }

    //每当行数达到设置的值就刷新数据到硬盘,以清理内存

    if(i%FLUSH_ROWS==0){

    ((SXSSFSheet)sheet).flushRows();

    }

    }

    }

    } catch (Exception e) {

    throw new Exception(e);

    }

    }

    /**

    * 07、10办公版EXCEL导出,单元格设置

    * @param cell 单元格对象

    * @param text 单元格文本内容

    * @param cellStyle 单元格格式

    */

    private static void setExcelCellText2007(Cell cell, Object text,CellStyle cellStyle)

    {

    cell.setCellValue(text.toString());

    cell.setCellType(1);//单元格类型

    cell.setCellStyle(cellStyle);

    }

    /**

    * 07、10办公版EXCEL导出,单元格宽度设置

    * @param widthList 列宽集合

    * @param sheet sheet对象

    * @param allSize 总列数

    */

    private static void setColumnWidth2007(List widthList,Sheet sheet,int allSize){

    if(widthList!=null && widthList.size()>0){

    int size=widthList.size();

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

    try {

    Integer width=Integer.parseInt((String) widthList.get(i));

    sheet.setColumnWidth((short) i,width*256);

    } catch (NumberFormatException e) {

    continue;

    }

    }

    }else{

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

    try {

    sheet.setColumnWidth((short) i,COLUMN_WIDTH_WORD*256);

    } catch (NumberFormatException e) {

    continue;

    }

    }

    }

    }

    /**

    * 03、WPS:EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据)

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param result 数字字典Map集

    * @param filePath 服务器存放文件路径

    * @param fileName 文件名称

    * @param totalSize EXCEL条数量

    * @param maxSheetSize sheet页条数量

    * @return List 文件集合

    * @throws Exception

    */

    public static List beans2excelFile03(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{

    if(totalSize==null || totalSize<=0)

    totalSize=TOTAL_SIZE;

    if(maxSheetSize==null || maxSheetSize<=0)

    maxSheetSize=MAX_SHEET_SIZE;

    if(fileName==null)

    fileName="";

    return beans2excelFile2003(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);

    }

    /**

    * 03、WPS:EXCEL导出(数据直接写到服务器的EXCEL里,以下载的形式,下载导出的数据)

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param result 数字字典Map集

    * @param filePath 服务器存放文件路径

    * @param fileName 文件名称

    * @param totalSize EXCEL条数量

    * @param maxSheetSize sheet页条数量

    * @param request 客户端请求对象

    * @param response 客户端响应对象

    * @throws Exception

    */

    public static void beans2excelFile03(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize,HttpServletRequest request,HttpServletResponse response) throws Exception{

    if(totalSize==null || totalSize<=0)

    totalSize=TOTAL_SIZE;

    if(maxSheetSize==null || maxSheetSize<=0)

    maxSheetSize=MAX_SHEET_SIZE;

    if(fileName==null)

    fileName="";

    List files=beans2excelFile2003(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);

    DownLoadUtils.downLoadFiles(files, filePath, request, response);

    }

    /**

    * 03、WPS:EXCEL导出,每个EXCEL组织数据

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param result 数字字典Map集

    * @param filePath 服务器存放文件路径

    * @param fileName 文件名称

    * @param totalSize EXCEL条数量

    * @param maxSheetSize sheet页条数量

    * @return 文件集合

    * @throws Exception

    */

    private static List beans2excelFile2003(List listName,List beans,HashMap> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{

    if ((listName == null) || (listName.size() == 0)) {

    throw new Exception("listName is null when create excel document");

    }

    List listFile=new ArrayList();//返回的文件集合

    int size=beans==null?0:beans.size();

    String fileSuffixName=".xls";//后缀

    String path="";//文件路径

    Integer startIdx=0;//数据读取的起始行

    Integer endIdx=0;//数据读取的结束行

    (new File(filePath)).mkdirs(); //没有该目录创建目录

    if(size==0){

    startIdx=0;

    endIdx=(totalSize)>size?size:(totalSize);

    String name=fileName+"_第0-0条数据";

    path=filePath+File.separatorChar+name+fileSuffixName;

    HSSFWorkbook wb =new HSSFWorkbook();

    buildExcelDocument2003(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);

    //没有文件,创建文件

    File file = new File(path);

    if (!file.exists()){

    file.createNewFile();

    }

    FileOutputStream out=new FileOutputStream(file);

    wb.write(out);

    out.close();

    return listFile;

    }

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

    int remainder=i%totalSize;

    if(size==0 || remainder==0){

    startIdx=i;

    endIdx=(i+totalSize)>size?size:(i+totalSize);

    String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据";

    path=filePath+"/"+name+fileSuffixName;

    HSSFWorkbook wb =new HSSFWorkbook();

    buildExcelDocument2003(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);

    //没有文件,创建文件

    File file = new File(path);

    if (!file.exists()){

    file.createNewFile();

    }

    FileOutputStream out=new FileOutputStream(file);

    wb.write(out);

    out.close();

    listFile.add(file);

    }else if((size-i)endIdx){//最后,不满一万条

    startIdx=i;

    endIdx=i+totalSize;

    String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"条数据";

    path=filePath+name+"."+fileSuffixName;//没有文件,创建文件

    HSSFWorkbook wb =new HSSFWorkbook();

    buildExcelDocument2003(wb, listName, beans, result,startIdx,endIdx,maxSheetSize);

    //没有文件,创建文件

    File file = new File(path);

    if (!file.exists()){

    file.createNewFile();

    }

    FileOutputStream out=new FileOutputStream(file);

    wb.write(out);

    out.close();

    listFile.add(file);

    }

    }

    return listFile;

    }

    /**

    * 03,WPS:EXCEL导出,每个EXCEL写入数据

    * @param wb EXCEL工作薄

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param result 数字字典Map集

    * @param startIdx 数据集合,开始行

    * @param endIdx 数据集合,结束始行

    * @param maxSheetSize SHEET页条数

    * @throws Exception

    */

    private static void buildExcelDocument2003(HSSFWorkbook wb, List listName, List beans,HashMap> result,Integer startIdx,Integer endIdx,Integer maxSheetSize) throws Exception

    {

    int totalSize=endIdx-startIdx;//总共条数

    try

    {

    CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);

    List titles = new ArrayList();

    List beanAttrNames = new ArrayList();

    List widthList=new ArrayList();

    String[] header = new String[listName.size()];

    List flagList=new ArrayList();

    boolean flagListExists=false;

    int rows_max = 0;//标题占多少列

    HashMap dateMap=new HashMap();

    for (int i=0;i

    {

    String[] str=listName.get(i).split("&");

    String en_name=str[0];

    String zh_name=str[1];

    beanAttrNames.add(i,en_name);

    titles.add(i, zh_name);

    header[i]=zh_name;

    if (zh_name.split("_").length > rows_max) {

    rows_max = zh_name.split("_").length;

    }

    if(str.length>2){

    String flag=str[2];

    flagList.add(i,flag);

    if(!flagListExists)

    flagListExists=true;

    }

    if(str.length>3){

    widthList.add(str[3]);

    }

    if(str.length>4){

    dateMap.put(en_name, str[4]);

    }

    }

    PropertyDescriptor[] props = null;

    int size=endIdx-startIdx;

    HSSFSheet sheet=null;

    //如果没有数据,导出表头

    if(size==0){

    sheet=ExcelHeadUtils.getExcelHead2003(wb, header, "Sheet1");

    sheet.setDefaultRowHeight((short)350);//高度

    setColumnWidth2003(widthList, sheet,beanAttrNames.size());

    return ;

    }

    int u=1;//用来创建每个sheet的行

    int h=0;//用来标注每个sheet也得名字:多少行-多少行

    for (int i = startIdx; i < endIdx ; i++) {

    int remainder=h%maxSheetSize;

    if(size==0 || i==startIdx || remainder==0){

    u=1;

    int section=(h+maxSheetSize)>totalSize?totalSize:(h+maxSheetSize);

    sheet=ExcelHeadUtils.getExcelHead2003(wb, header, "第"+(h+1)+"-"+section+"条");

    sheet.createFreezePane( 1, rows_max, 1, rows_max);

    sheet.setDefaultRowHeight((short)350);//高度

    setColumnWidth2003(widthList, sheet,beanAttrNames.size());

    }

    if(props==null)

    props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();

    Object bean = beans.get(i);

    HSSFRow row = sheet.createRow(u+rows_max-1);

    u++;

    h++;

    for (int j = 0; j < beanAttrNames.size(); j++) {

    String beanAttrName = (String)beanAttrNames.get(j);

    String flag=null;

    if(flagListExists)

    flag=(String)flagList.get(j);

    for (int k = 0; k < props.length; k++) {

    String propName = props[k].getName();

    if (propName.equals(beanAttrName))

    {

    String pattern=dateMap.get(beanAttrName);

    HSSFCell cell = row.createCell((short)j);

    Object cellValue = callGetter(bean, props[k],pattern);

    if("true".equalsIgnoreCase(flag)){

    if(result!=null){

    HashMap hash=result.get(beanAttrName);

    if(hash!=null)

    cellValue=hash.get(cellValue);

    }

    }

    if (cellValue == null) {

    cellValue = "";

    }

    setExcelCellText2003(cell, cellValue.toString(),cellStyle);

    }

    }

    }

    }

    } catch (Exception e) {

    throw new Exception(e);

    }

    }

    /**

    * 03,WPS:EXCEL导出(直接以流的方式,写到客户端,导出的EXCEL文件只有一个)

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param maxSheetSize sheet页条数量

    * @param outputStream 客户端输出流

    * @throws Exception

    */

    public static void beans2excelFile03(List listName,List beans,HashMap> result,String sheetName,Integer maxSheetSize, OutputStream outputStream) throws Exception{

    if ((listName == null) || (listName.size() == 0)) {

    throw new Exception("listName is null when create excel document");

    }

    if(maxSheetSize==null || maxSheetSize<=0){

    maxSheetSize=MAX_SHEET_SIZE;

    }

    if(sheetName==null || "".equals(sheetName.trim())){

    sheetName="Sheet";

    }

    HSSFWorkbook wb =new HSSFWorkbook();

    if(maxSheetSize==null || maxSheetSize<=0)

    maxSheetSize=MAX_SHEET_SIZE;

    buildExcelDocument2003(wb, listName, beans,result,sheetName,maxSheetSize);

    try {

    wb.write(outputStream);

    outputStream.close();

    } catch (IOException e) {

    throw new Exception(e);

    }

    }

    /**

    * 03,WPS:EXCEL导出,EXCEL写入数据

    * @param wb EXCEL工作薄

    * @param listName 列表头名称

    * @param beans 实体集合

    * @param maxSheetSize sheet页条数量

    * @throws Exception

    */

    private static void buildExcelDocument2003(HSSFWorkbook wb, List listName, List beans,HashMap> result,String sheetName,Integer maxSheetSize) throws Exception

    {

    try

    {

    CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);

    List titles = new ArrayList();

    List beanAttrNames = new ArrayList();

    List widthList = new ArrayList();

    HashMap dateMap=new HashMap();

    String[] header = new String[listName.size()];

    int rows_max = 0;//标题占多少列

    List flagList=new ArrayList();

    boolean flagListExists=false;

    for (int i=0;i

    {

    String[] str=listName.get(i).split("&");

    String en_name=str[0];

    String zh_name=str[1];

    beanAttrNames.add(i,en_name);

    titles.add(i, zh_name);

    header[i]=zh_name;

    if (zh_name.split("_").length > rows_max) {

    rows_max = zh_name.split("_").length;

    }

    if(str.length>2){

    String flag=str[2];

    flagList.add(i,flag);

    if(!flagListExists)

    flagListExists=true;

    }

    if(str.length>3){

    widthList.add(str[3]);

    }

    if(str.length>4){

    dateMap.put(en_name, str[4]);

    }

    }

    PropertyDescriptor[] props =null;

    int size=beans==null?0:beans.size();

    HSSFSheet sheet=null;

    //如果没有数据,导出表头

    if(size==0){

    sheet=ExcelHeadUtils.getExcelHead2003(wb, header, sheetName);

    setColumnWidth2003(widthList, sheet,beanAttrNames.size());

    sheet.setDefaultRowHeight((short)350);//高度

    return ;

    }

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

    int remainder=i%maxSheetSize;

    if(size==0 || i==0 || remainder==0){

    sheet=ExcelHeadUtils.getExcelHead2003(wb, header, sheetName+(i/maxSheetSize));

    sheet.createFreezePane( 1, rows_max, 1, rows_max);

    setColumnWidth2003(widthList, sheet,beanAttrNames.size());

    sheet.setDefaultRowHeight((short)350);//高度

    }

    if(props==null)

    props= Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();

    Object bean = beans.get(i);

    HSSFRow row = sheet.createRow(remainder+rows_max);

    for (int j = 0; j < beanAttrNames.size(); j++) {

    String beanAttrName = (String)beanAttrNames.get(j);

    String flag=null;

    if(flagListExists)

    flag=(String)flagList.get(j);

    for (int k = 0; k < props.length; k++) {

    String propName = props[k].getName();

    if (propName.equals(beanAttrName))

    {

    String pattern=dateMap.get(beanAttrName);

    HSSFCell cell = row.createCell((short)j);

    Object cellValue = callGetter(bean, props[k],pattern);

    if("true".equalsIgnoreCase(flag)){

    if(result!=null){

    HashMap hash=result.get(beanAttrName);

    if(hash!=null)

    cellValue=hash.get(cellValue);

    }

    }

    if (cellValue == null) {

    cellValue = "";

    }

    setExcelCellText2003(cell, cellValue.toString(),cellStyle);

    }

    }

    }

    }

    } catch (Exception e) {

    throw new Exception(e);

    }

    }

    /**

    * 03,WPS:EXCEL导出,单元格设置

    * @param cell 单元格对象

    * @param text 单元格文本内容

    * @param cellStyle 单元格格式

    */

    private static void setExcelCellText2003(HSSFCell cell, Object text,CellStyle cellStyle)

    {

    cell.setCellValue(text.toString());

    cell.setCellType(1);//单元格类型

    cell.setCellStyle(cellStyle);

    }

    /**

    * 03,WPS:EXCEL导出,单元格宽度设置

    * @param widthList 列宽集合

    * @param sheet sheet对象

    * @param allSize 总列数

    */

    private static void setColumnWidth2003(List widthList,HSSFSheet sheet,int allSize){

    if(widthList!=null && widthList.size()>0){

    int size=widthList.size();

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

    try {

    Integer width=Integer.parseInt((String) widthList.get(i));

    sheet.setColumnWidth((short) i,width*256);

    } catch (NumberFormatException e) {

    continue;

    }

    }

    }else{

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

    try {

    sheet.setColumnWidth((short) i,COLUMN_WIDTH_WORD*256);

    } catch (NumberFormatException e) {

    continue;

    }

    }

    }

    }

    /**

    * 根据反射,获取实体属性的值

    * @param target 实体属性

    * @param prop 反射调用类

    * @param pattern 日期格式

    * @return

    */

    private static Object callGetter(Object target, PropertyDescriptor prop,String pattern) {

    Object o = null;

    if (prop.getReadMethod() != null) {

    try {

    o = prop.getReadMethod().invoke(target, null);

    if (Date.class.equals(prop.getPropertyType())) {

    if(pattern!=null && !"".equals(pattern)){

    try {

    o = new SimpleDateFormat(pattern).format(o);

    } catch (Exception e) {

    o = new SimpleDateFormat(PATTERN).format(o);

    }

    }else{

    o = formatDate(o);

    }

    }

    } catch (Exception e) {

    o = null;

    }

    }

    return o;

    }

    /**

    * 日期转换

    * @param date

    * @return 字符串的日期

    */

    private static String formatDate(Object date) {

    if(date==null)

    return "";

    String dateStr = new SimpleDateFormat(DATE_HH_PATTERN).format(date);

    if("00:00:00".equals(dateStr)){

    return new SimpleDateFormat(DATE_PATTERN).format(date);

    }

    return new SimpleDateFormat(PATTERN).format(date);

    }

    }

    然后看看效果吧:

    91da5eb4f838113f2366468e1fd67255.png

    &lbrack;转载&rsqb;Java导出Excel

    一.需求介绍 当前B/S模式已成为应用开发的主流,而在开发企业办公系统的过程中,常常有客户这样子要求:把系统数据库中的数据导出到Excel,用户查看报表时直接用Excel打开.或者是:用户已经习惯用E ...

    java导出excel报错:getOutputStream&lpar;&rpar; has already been called for this response

    对于java导出excel报错的问题,查了很多都说是在使用完输出流以后调用以下两行代码即可 out.clear(); out = pageContext.pushBody(); 但这也许是页面上输出时 ...

    java导出excel报表

    1.java导出excel报表: package cn.jcenterhome.util; import java.io.OutputStream;import java.util.List;impo ...

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

    java导出excel表格

    java导出excel表格: 1.导入jar包 org.apache.poi

    Java导出Excel和CSV&lpar;简单Demo&rpar;

    Java导出Excel和CSV的简单实现,分别使用POI和JavaCSV. JavaBean public class ReportInfo { int id; String date; int nu ...

    java导出excel模板数据

    Java导出excel数据模板,这里直接贴代码开发,流程性的走下去就是步骤: String[] colName=new String[]{"期间","科目代码" ...

    java导出excel工具类

    java导出excel须要使用HSSFWorkbook这个类,须要导入poi-3.6-20091214.jar 工具类调用例如以下: package com.qlwb.business.util; i ...

    JAVA 导出 Excel, 将Excel下载到本地

    昨天说了如何将数据导出成 excel 的两种方式,今天完善一下将 java 导出(文件在服务器)并下载到本地 1. 触发导出 ajax 代码 $.ajax({ type: "POST&quo ...

    随机推荐

    PHP文件大小格式化函数合集

    比如碰到一个很大的文件有49957289167B,大家一看这么一长串的数字后面单位是字节B,还是不知道这个文件的大小是一个什么概念,我们把它转换成GB为单位,就是46.53GB.用下面这些函数就可以完 ...

    通用PE工具箱 4&period;0精简优化版

    通用PE工具箱 4.0精简优化版 经用过不少 WinPE 系统,都不是很满意,普遍存在篡改主页.添加广告链接至收藏夹.未经允许安装推广软件等流氓行为,还集成了诸多不常用的工具,令人头疼不已.那么今天给 ...

    C&num;中timer类的用法

    C#中timer类的用法 关于C#中timer类  在C#里关于定时器类就有3个   1.定义在System.Windows.Forms里   2.定义在System.Threading.Timer类 ...

    如何用linux命令查看nginx是否在正常运行

    有时想知道nigix是否在正常运行,需要用linux命令查看nginx运行情况. 执行命令: ps -A | grep nginx  如果返回结果的话,说明有nginx在运行,服务已经启动. 如果 ...

    JavaScript----遇到的问题

    存在 ...

    vector内存分配

    vector,map 这些容器还是在堆上分配的内存,在析构时是释放空间 vector在提高性能可以先reserve在push_back() reserve:决定capacity,但没有真正的分配内存, ...

    Listview加载更多是,恢复到原来的位置,如果不加特殊处理,总是跳转第一条

    1.记录listView滚动到的位置的坐标,然后利用listView.scrollTo精确的进行恢复 listView.setOnScrollListener(new OnScrollListener ...

    自然语言&period;例如&colon;求n&excl;。

    (1).定义3个变量i.n及mul,并为i和mul均赋初值为1. (2).从键盘中输入一个数赋给n. (3).将mul乘以i的结果赋给mul. (4)i的值加1,判断i的值是否大于n.如果大于n,则执 ...

    &lbrack;APIO2010&rsqb;

    A.特别行动队 n<=1000000 看了数据范围和题目感觉就像是斜率优化,然后瞎推了一波式子,没想到A了. sij表示i+1到j的权值和. j比k优秀  $$fj+a*sij^{2}+b*si ...

    md5 加密文件

    import hashlibimport os def get_md5(file_path): md5 = None if os.path.isfile(file_path): f = open(fi ...

    展开全文
  • ServletActionContext.getResponse().setContentType("application/vnd.ms-excel"); String filename = starttime+"-"+endtime+"来访客户统计表.xls"; String agent = ServletActionContext.getRequest().getHeader...
  • 这篇文章主要介绍了JavaWeb动态导出Excel,对Excel可弹出进行下载操作,感兴趣的小伙伴们可以参考一下由于项目需求,需要将数据导出成Excel表格,并且可选择导出项,可下载。项目使用的Spring+Mybatis+SpringMVC框架...
  • 一、引言在Java Web开发中经常涉及到报表,最近做的项目中需要实现将数据库中的数据显示为表格,并且实现导出Excel文件的功能。二、相关jar包使用POI可以很好的解决Excel的导入和导出的问题,POI下载地址:poi-3.6...
  • packagecom.test.demo.controllers;importcom.test.demo.domain.entities....importcom.test.demo.services.ExcelService;importjxl.Workbook;importjxl.format.Alignment;importjxl.format.Border;importjxl.f...
  • 闲着整理了下java导出excel的一些步骤,也是网上摘抄的,简单的测试,先跑通是怎么玩了,走走debug就大概知道个什么东西了,先能用,再去理解,已经测试可以用的! 1、导入所需要的jar包 <!-- excel 引用包 -->...
  • importjava.beans.Introspector;importjava.beans.PropertyDescriptor;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.OutputStream;importjava.text.SimpleDateForma...
  • 在项目中需要将数据导出excel并共用户下载,经过在网络查询资料参考文档花了半天完成了excel导出和下载,现在分享给大家。开发环境:maven+spring+spingMvc,需要使用poi相关jar包,请在pom文件中配置1.页面调用请求...
  • java导出Excel并下载到本地

    千次阅读 2020-03-04 21:00:20
    "application/vnd.ms-excel" ) ; // 下载文件的默认名称 response . setHeader ( "Content-Disposition" , "attachment;filename=" + URLEncoder . encode ( fileName , "utf-8" ) ) ; exportExcel ...
  • 我们使用的导出并下载功能是利用一个插件叫POI的插件提供的导出功能,很实用;首先先导入Jar包: Jar包下载地址:http://poi.apache.org/ 官方文档地址:http://poi.apache.org/spreadsheet/quick-guide.html ...
  • 在项目中需要将数据导出excel并共用户下载,经过在网络查询资料参考文档花了半天完成了excel导出和下载,现在分享给大家。 开发环境:maven+spring+spingMvc,需要使用poi相关jar包,请在pom文件中配置 1.页面...
  • https://www.cnblogs.com/raphael5200/p/5132631.html
  • 本文简单实现java导出excel并下载的功能。其中,java导出excel使用的是Apache poi技术,使用之前需要在项目中引入相关的jar包。poi相关技术之前有过探讨,在此不再赘述。关于下载的功能实现,一种是通过超链接指向...
  • ServletActionContext.getResponse().setContentType("application/vnd.ms-excel"); String filename = starttime+"-"+endtime+"来访客户统计表.xls"; String agent = ServletActionContext.getRequest().getHeader...
  • @Overridepublic voidexport(Long sblsh, String excelName, OutputStream out) {try{//第一步,创建一个webbook,对应一个Excel文件HSSFWorkbook wb = newHSSFWorkbook();//生成一个表格HSSFSheet sheet =wb....
  • 问题描述:java批量导出excel压缩下载问题分析:考虑两种方案:1.将单个excel下载到指定的磁盘,然后读取压缩下载。2.在程序中创建多个excel文佳,压缩下载。最后考虑简洁,快速,采用第二种解决方案。解决方案...
  • ServletActionContext.getResponse().setContentType("application/vnd.ms-excel"); String filename = starttime+"-"+endtime+"来访客户统计表.xls"; String agent = ServletActionContext.getRequest().getHeader...
  • /*** 导出Excel* @author Saffi*/@RequestMapping("exportExcel.action")public void exportExcel(HttpServletResponse response) throws IOException {try {// 查询赋给List集合List oddList = entityService....
  • Java poi 导出Excel并下载到客户端,具体内容如下Maven配置,包含了其他文件格式的依赖,就全贴出来了org.apache.poipoi-excelant3.12org.apache.poipoi-scratchpad3.12org.apache.poipoi-ooxml3.8org.apache.poipoi...
  • Java导出Excel并弹出下载

    千次阅读 2018-02-09 16:23:42
    项目使用的Spring+Mybatis+SpringMVC框架,利用Apache POI导出Excel。POI具体使用请自行百度。话不多说,上代码。ExportExcelUtil代码package com.rixin.common.util; import java.io.OutputStream; import java.l.....
  • [Java教程]Springmvc和poi3.9导出excel并弹出下载框0 2013-09-06 20:00:07Springmvc 和 poi3.9 用java程序从数据库导出数据到excel(在博客园的第一篇原创博客)@RequestMapping(value = "/importexcel.htm", method =...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 432
精华内容 172
关键字:

java导出excel并下载

java 订阅