第一版代碼:
基礎功能跳轉此文章java自定義Excel導出工具:
簡介
新增功能:
- 添加自定義字段導出功能, 用戶可以選擇字段進行導出
- 將字典類型數據進行轉換(如:0=女,1=男, 將0轉換為女, 1轉換為男)
- 添加表頭格式
- 隨機文件名稱, 防止多次導出時文件覆蓋問題
實現代碼
Excel注解
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Excel { /** * 導出到Excel中的名字 */ String name() default ""; /** * 日期格式, 如: yyyy-MM-dd */ String dateFormat() default ""; /** * 字典的key值 */ String dictKey() default ""; /** * 讀取內容轉表達式 (如: 0=男,1=女,2=未知) */ String dictExp() default ""; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
Excel的導出工具類
/** * Excel的工具類 */ public class ExcelUtil<T> { /** * 工作薄 */ private Workbook wb; /** * 工作表 */ private Sheet sheet; /** * 需要導出的數據 */ private List<T> exportList; /** * 對象的class對象 */ private Class<T> clazz; /** * 被選中需要導出的字段名稱 */ private Map<String, Object> checkedFieldsName; /** * 被選中需要導出的字段對象 */ private List<Field> checkedFields; /** * 包含需要字典轉換的字段對象 */ private List<Field> fieldsContainDict; /** * 對象中的字典值 */ private Map<String, Map<String, String>> dicts; private ExcelUtil(){ } public ExcelUtil(Class<T> clazz){ this.clazz = clazz; } /** * * @param list * @param sheetName * @param fieldsName */ public void exportExcel(List<T> list, Map<String, Object> fieldsName, String sheetName){ // 初始化數據 init(list, sheetName, fieldsName); // 轉換字典值 try { convertDict(); } catch (IllegalAccessException e) { e.printStackTrace(); } // sheet第一行加入名稱數據 createTopRow(); // sheet其他行,添加目標數據 try { createOtherRow(); } catch (IllegalAccessException e) { e.printStackTrace(); } // 導出wb try(OutputStream outFile = new FileOutputStream(generateFileName())){ wb.write(outFile); } catch (IOException e) { e.printStackTrace(); } finally { try { wb.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 添加導出數據 */ private void createOtherRow() throws IllegalAccessException { for (int rowNum = 1; rowNum <= exportList.size(); rowNum++) { Row row = sheet.createRow(rowNum); T t = exportList.get(rowNum - 1); for (int colNum = 0; colNum < checkedFields.size(); colNum++) { Cell cell = row.