引入maven
<!--excel導出-->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<!--工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>[4.1.12,)</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!--lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
導出excel工具類
package com.test.cms.excel; import cn.hutool.core.util.ObjectUtil; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.*; import java.util.Map.Entry; public class ExcelUtils { /** * @param list 數據源 * @param fieldMap 類的英文屬性和Excel中的中文列名的對應關系 * @param sheetName 工作表的名稱 * @param sheetSize 每個工作表中記錄的最大個數 * @param out 導出流 * @throws Exception * @MethodName : listToExcel * @Description : 導出Excel(可以導出到本地文件系統,也可以導出到瀏覽器,可自定義工作表大小) */ public static <T> void listToExcel( List<T> list, LinkedHashMap<String, String> fieldMap, String sheetName, int sheetSize, OutputStream out ) throws Exception { if (list == null || list.size() == 0) { throw new Exception("數據源中沒有任何數據"); } if (sheetSize > 65535 || sheetSize < 1) { sheetSize = 65535; } //創建工作簿並發送到OutputStream指定的地方 WritableWorkbook wwb; try { wwb = Workbook.createWorkbook(out); //因為2003的Excel一個工作表最多可以有65536條記錄,除去列頭剩下65535條 //所以如果記錄太多,需要放到多個工作表中,其實就是個分頁的過程 //1.計算一共有多少個工作表 double sheetNum = Math.ceil(list.size() / new Integer(sheetSize).doubleValue()); //2.創建相應的工作表,並向其中填充數據 for (int i = 0; i < sheetNum; i++) { //如果只有一個工作表的情況 if (1 == sheetNum) { WritableSheet sheet = wwb.createSheet(sheetName, i); fillSheet(sheet, list, fieldMap, 0, list.size() - 1); //有多個工作表的情況 } else { WritableSheet sheet = wwb.createSheet(sheetName + (i + 1), i); //獲取開始索引和結束索引 int firstIndex = i * sheetSize; int lastIndex = (i + 1) * sheetSize - 1 > list.size() - 1 ? list.size() - 1 : (i + 1) * sheetSize - 1; //填充工作表 fillSheet(sheet, list, fieldMap, firstIndex, lastIndex); } } wwb.write(); wwb.close(); } catch (Exception e) { e.printStackTrace(); //如果是Exception,則直接拋出 if (e instanceof Exception) { throw (Exception) e; //否則將其它異常包裝成Exception再拋出 } else { throw new Exception("導出Excel失敗"); } } } /** * @param list 數據源 * @param fieldMap 類的英文屬性和Excel中的中文列名的對應關系 * @param sheetSize 每個工作表中記錄的最大個數 * @param response 使用response可以導出到瀏覽器 * @throws Exception * @MethodName : listToExcel * @Description : 導出Excel(導出到瀏覽器,可以自定義工作表的大小) */ public static <T> void listToExcel( List<T> list, LinkedHashMap<String, String> fieldMap, String sheetName, int sheetSize, HttpServletResponse response ) throws Exception { //設置默認文件名為當前時間:年月日時分秒 String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString(); //設置response頭信息 response.reset(); response.setContentType("application/vnd.ms-excel"); //改成輸出excel文件 response.setHeader("Content-disposition", "attachment; filename=" + new String(sheetName.getBytes(), "iso-8859-1") + ".xls"); //創建工作簿並發送到瀏覽器 try { OutputStream out = response.getOutputStream(); listToExcel(list, fieldMap, sheetName, sheetSize, out); } catch (Exception e) { e.printStackTrace(); //如果是Exception,則直接拋出 if (e instanceof Exception) { throw (Exception) e; //否則將其它異常包裝成Exception再拋出 } else { throw new Exception("導出Excel失敗"); } } } /** * @param list 數據源 * @param fieldMap 類的英文屬性和Excel中的中文列名的對應關系 * @param response 使用response可以導出到瀏覽器 * @throws Exception * @MethodName : listToExcel * @Description : 導出Excel(導出到瀏覽器,工作表的大小是2003支持的最大值) */ public static <T> void listToExcel( List<T> list, LinkedHashMap<String, String> fieldMap, String sheetName, HttpServletResponse response ) throws Exception { listToExcel(list, fieldMap, sheetName, 65535, response); } /** * @param fieldName 字段名 * @param o 對象 * @return 字段值 * @MethodName : getFieldValueByName * @Description : 根據字段名獲取字段值 */ private static Object getFieldValueByName(String fieldName, Object o) throws Exception { Object value = null; Field field = getFieldByName(fieldName, o.getClass()); if (field != null) { field.setAccessible(true); value = field.get(o); } else { throw new Exception(o.getClass().getSimpleName() + "類不存在字段名 " + fieldName); } return value; } /** * @param fieldName 字段名 * @param clazz 包含該字段的類 * @return 字段 * @MethodName : getFieldByName * @Description : 根據字段名獲取字段 */ private static Field getFieldByName(String fieldName, Class<?> clazz) { //拿到本類的所有字段 Field[] selfFields = clazz.getDeclaredFields(); //如果本類中存在該字段,則返回 for (Field field : selfFields) { if (field.getName().equals(fieldName)) { return field; } } //否則,查看父類中是否存在此字段,如果有則返回 Class<?> superClazz = clazz.getSuperclass(); if (superClazz != null && superClazz != Object.class) { return getFieldByName(fieldName, superClazz); } //如果本類和父類都沒有,則返回空 return null; } /** * @param fieldNameSequence 帶路徑的屬性名或簡單屬性名 * @param o 對象 * @return 屬性值 * @throws Exception * @MethodName : getFieldValueByNameSequence * @Description : * 根據帶路徑或不帶路徑的屬性名獲取屬性值 * 即接受簡單屬性名,如userName等,又接受帶路徑的屬性名,如student.department.name等 */ private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception { Object value = null; //將fieldNameSequence進行拆分 String[] attributes = fieldNameSequence.split("\\."); if (attributes.length == 1) { value = getFieldValueByName(fieldNameSequence, o); } else { //根據屬性名獲取屬性對象 Object fieldObj = getFieldValueByName(attributes[0], o); String subFieldNameSequence = fieldNameSequence.substring(fieldNameSequence.indexOf(".") + 1); value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj); } return value; } /** * @param ws * @MethodName : setColumnAutoSize * @Description : 設置工作表自動列寬和首行加粗 */ private static void setColumnAutoSize(WritableSheet ws, int extraWith) { //獲取本列的最寬單元格的寬度 for (int i = 0; i < ws.getColumns(); i++) { int colWith = 0; for (int j = 0; j < ws.getRows(); j++) { String content = ws.getCell(i, j).getContents().toString(); int cellWith = content.length(); if (colWith < cellWith) { colWith = cellWith; } } //設置單元格的寬度為最寬寬度+額外寬度 ws.setColumnView(i, colWith + extraWith); } } /** * @param sheet 工作表 * @param list 數據源 * @param fieldMap 中英文字段對應關系的Map * @param firstIndex 開始索引 * @param lastIndex 結束索引 * @MethodName : fillSheet * @Description : 向工作表中填充數據 */ private static <T> void fillSheet( WritableSheet sheet, List<T> list, LinkedHashMap<String, String> fieldMap, int firstIndex, int lastIndex ) throws Exception { //定義存放英文字段名和中文字段名的數組 String[] enFields = new String[fieldMap.size()]; String[] cnFields = new String[fieldMap.size()]; //填充數組 int count = 0; for (Entry<String, String> entry : fieldMap.entrySet()) { enFields[count] = entry.getKey(); cnFields[count] = entry.getValue(); count++; } //填充表頭 for (int i = 0; i < cnFields.length; i++) { Label label = new Label(i, 0, cnFields[i]); sheet.addCell(label); } //填充內容 int rowNo = 1; for (int index = firstIndex; index <= lastIndex; index++) { //獲取單個對象 T item = list.get(index); for (int i = 0; i < enFields.length; i++) { Object objValue = getFieldValueByNameSequence(enFields[i], item); if (objValue instanceof Date) { objValue = date2Str((Date) objValue, "yyyy-MM-dd HH:mm:ss"); } String fieldValue = (objValue == null) ? "" : objValue.toString(); Label label = new Label(i, rowNo, fieldValue); sheet.addCell(label); } rowNo++; } //設置自動列寬 setColumnAutoSize(sheet, 5); } public static String date2Str(Date date, String formats) { return ObjectUtil.isEmpty(date) ? null : (new SimpleDateFormat(formats)).format(date); } }
測試導出的實體類
package com.test.cms.excel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @Data @Accessors(chain = true) @AllArgsConstructor @NoArgsConstructor public class ExcelDTO { private String name; private String operator; }
導出控制器類
package com.test.cms.controller; import com.test.cms.excel.ExcelDTO; import com.test.cms.excel.ExcelUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @RestController public class ExcelController { @RequestMapping("/excel/export") public void test(HttpServletResponse response){ List<ExcelDTO> records = new ArrayList(); //添加測試數據 for (int i=0;i<10;i++){ ExcelDTO dto=new ExcelDTO("name"+i,"operator"+i); records.add(dto); } LinkedHashMap<String, String> titleMap = getTitleMap(); try { ExcelUtils.listToExcel(records, titleMap, "文檔名稱", response); } catch (Exception e) { e.printStackTrace(); } } /** * d導出標題欄 * * @return */ private static LinkedHashMap<String, String> getTitleMap() { LinkedHashMap<String, String> names = new LinkedHashMap<String, String>(); //name和operator是ExcelDTO實體類的屬性名,姓名表示name列表頭顯示的名稱 names.put("name", "姓名"); names.put("operator", "操作人"); return names; } }