在实际项目开发中,有时需要多次下载excel报表,以此专门开发写入excel的工具类
- 这工具采用POI的HSSF和SXSSF两种API进行下载,可实现几万条(HSSF)和百万条(SXSSF)的写入,当数据大小超过23000条(可改)时自动切换API进行写入。
- 使用Collection容器装载需要写入的数据,这您就需要专门写bean来保存对象值。当然还有其他方式,比如使用json来保存写入数据,但是在实际开发中遇到问题:遍历json数组写入excel时,并没有按json对象名称的顺序写入,比如https://bbs.csdn.net/topics/390531037,现在还没有找到满意的答案。
- 以及在实际开发中,遇到的各种问题和解决方案,希望能对您有帮助
- 需要的jar:https://download.csdn.net/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