有些时候需要导出一些报表到EXCEL,下面介绍一个简单的方法,封装好工具类后只需要准备参数和路径即可。
使用jxl,只能处理2003的excel(xls)
首先导入JAR包
<dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6.10</version> </dependency>
1 public static void writeExcel(List<Map<String, Object>> list, String path) { 2 try { 3 // Excel底部的表名 4 String sheetn = "table1"; 5 // 用JXL向新建的文件中添加内容 6 File myFilePath = new File(path); 7 if (!myFilePath.exists()) 8 myFilePath.createNewFile(); 9 OutputStream outf = new FileOutputStream(path); 10 WritableWorkbook wwb = Workbook.createWorkbook(outf); 11 jxl.write.WritableSheet writesheet = wwb.createSheet(sheetn, 1); 12 // 设置标题 13 if (list.size() > 0) { 14 int j = 0; 15 for (Entry<String, Object> entry : list.get(0).entrySet()) { 16 String title = entry.getKey(); 17 writesheet.addCell(new Label(j, 0, title)); 18 j++; 19 } 20 } 21 // 内容添加 22 for (int i = 1; i <= list.size(); i++) { 23 int j = 0; 24 for (Entry<String, Object> entry : list.get(i - 1).entrySet()) { 25 Object o = entry.getValue(); 26 if (o instanceof Double) { 27 writesheet.addCell(new jxl.write.Number(j, i, (Double) entry.getValue())); 28 } else if (o instanceof Integer) { 29 writesheet.addCell(new jxl.write.Number(j, i, (Integer) entry.getValue())); 30 } else if (o instanceof Float) { 31 writesheet.addCell(new jxl.write.Number(j, i, (Float) entry.getValue())); 32 } else if (o instanceof Float) { 33 writesheet.addCell(new jxl.write.DateTime(j, i, (Date) entry.getValue())); 34 } else if (o instanceof BigDecimal) { 35 writesheet.addCell(new jxl.write.Number(j, i, ((BigDecimal) entry 36 .getValue()).doubleValue())); 37 } else if (o instanceof Long) { 38 writesheet.addCell(new jxl.write.Number(j, i, ((Long) entry.getValue()) 39 .doubleValue())); 40 } else { 41 writesheet.addCell(new Label(j, i, (String) entry.getValue())); 42 } 43 j++; 44 } 45 } 46 wwb.write(); 47 wwb.close(); 48 } catch (WriteException e) { 49 e.printStackTrace(); 50 } catch (IOException e) { 51 e.printStackTrace(); 52 } 53 }
将它封装到工具类中,再调用,如下:
1 public static void main(String[] args) { 2 //数据准备 3 List<Map<String, Object>> list = new ArrayList<>(); 4 for (int i = 0; i < 1000; i++) { 5 Map<String, Object> map = new LinkedHashMap<>(); 6 map.put("ID", i+1000); 7 map.put("姓名", "NAME"+i); 8 map.put("地址", "address"+(i*2)); 9 list.add(map); 10 } 11 //存放路径 12 String path; 13 try { 14 //获取项目的路径 15 path = Class.class.getClass().getResource("/").getPath(); 16 System.out.println(path); 17 //路径转换下格式 18 path = path.replaceAll("classes", "excel").concat("Test").concat(".xls"); 19 System.out.println(path); 20 //写入到excel 21 writeExcel(list, path); 22 } catch (Exception e) { 23 e.printStackTrace(); 24 } 25 }
控制台输出路径:
效果如图: