这里封装了一个工具类,将对象的list集合解析生成表格,只要按照参数要求传参就好了。
工具类代码如下:
package com.hd.erpreport.utils; import java.io.File; import java.util.Iterator; import java.util.List; import com.google.gson.Gson; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JXLCreateExcelUtil { public static <T> void createExcel(List<T> list, String sheetName, int sheetNum, String path) { Gson gson = new Gson(); // JSONArray jsonArray = JSONArray.fromObject(list); try { //这里的path是包含文件名的,在传入之前要保证路径完整存在 WritableWorkbook book = Workbook.createWorkbook(new File(path)); WritableSheet sheet = book.createSheet(sheetName, sheetNum); int hang = 0; JSONObject jsonObject = JSONObject.fromObject(gson.toJson(list.get(0))); JSONArray jsonArray = JSONArray.fromObject(list); for (Object object : jsonArray) { JSONObject jsonObject1 = JSONObject.fromObject(object); @SuppressWarnings("rawtypes") Iterator iterator = jsonObject.keys(); int lie = 0; while (iterator.hasNext()) { sheet.addCell(new Label(lie++, hang, jsonObject1.getString((String) iterator.next()))); } hang++; } book.write(); book.close(); } catch (Exception e) { e.printStackTrace(); } } }
//list是需要生成表格的对象集合
//sheetName是sheet的名称
//sheetNum是第几个sheet
//path是包含文件名的path,所以要保证路径的完整存在