POI HSSF SXSSF 百万写入

本文介绍了在项目中利用Apache POI库的HSSF和SXSSF API,实现从几万到百万条数据的Excel下载。当数据量超过23000条时自动切换API,解决了内存溢出、单元格样式限制等问题,并提供了解决各种报错的方案。同时,分享了自适应列宽和调整内存大小等注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在实际项目开发中,有时需要多次下载excel报表,以此专门开发写入excel的工具类

  • 这工具采用POI的HSSF和SXSSF两种API进行下载,可实现几万条(HSSF)和百万条(SXSSF)的写入,当数据大小超过23000条(可改)时自动切换API进行写入。
  • 使用Collection容器装载需要写入的数据,这您就需要专门写bean来保存对象值。当然还有其他方式,比如使用json来保存写入数据,但是在实际开发中遇到问题:遍历json数组写入excel时,并没有按json对象名称的顺序写入,比如https://bbs.youkuaiyun.com/topics/390531037,现在还没有找到满意的答案。
  • 以及在实际开发中,遇到的各种问题和解决方案,希望能对您有帮助
  • 需要的jar:https://download.youkuaiyun.com/download/wushuoyouting/10976088
  • POI官网API:http://poi.apache.org/components/index.html

 

1.下载action 

@ResponseBody// 返回json
	@RequestMapping("/writeExcel")
	public String writeExcel(){
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletResponse response = requestAttributes.getResponse();
        HttpServletRequest request = requestAttributes.getRequest();
		
		JSONObject excelObj = new JSONObject();
		try {
			String title ="下载excel测试";
			// "微信订单号","导入日期"
			String[] headers = { "学号", "姓名", "年龄", "性别", "出生日期"};
                //需要新建Student对象 int id,String name,int age,int sex,Date birthday
		    List<Student> dataset = new ArrayList<Student>();
                //写入一百万条数据
		    for (int i = 0; i < 1000000; i++) {
			    dataset.add(new Student(i, "111111111111", 2222, 111111,new Date()));
		    } "");
			
			String filePath= request.getSession().getServletContext().getRealPath("/");
			String path = "";
			if(wcBills.size() < 23000) {
				path="excel\\writeExcel.xls";
			}else {
				path="excel\\writeExcel.xlsx";
			}
			filePath = filePath+path;
			writeExcelUtil<WechatBill> weu = new writeExcelUtil<WechatBill>();
			if(weu.writeExcel(title, headers, wcBills,filePath)){
				String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"//"+path;
				excelObj.put("msg", basePath);
			}
			
			excelObj.put("retcode", true);
		} catch (KyRuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackT
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值