• POI动态字段导出Excel-导入Excel,解析加密数据再导出


    一、POI动态字段导出Excel-导入Excel

    1.直接导出Excel

    1. public static void main(String[] args) throws IOException {
    2. // String filePath = "E:\\测试POI生成文件\\测试POI生成文件01.xls";
    3. // HSSFWorkbook workbook = new HSSFWorkbook();
    4. // HSSFSheet sheet = workbook.createSheet();
    5. // sheet = workbook.createSheet("测试POI生成文件01");
    6. // FileOutputStream out = new FileOutputStream(filePath);
    7. // workbook.write(out);
    8. // out.close();
    9. // 升级到 POI 3.5
    10. // TestController.test01();
    11. // TestController.test02();o
    12. String jsonString = "{\n" +
    13. " \"title\":\"查询表格\",\n" +
    14. " \"columns\":[\n" +
    15. " [\n" +
    16. " {\n" +
    17. " \"title\":\"序号\",\n" +
    18. " \"field\":\"SEQ\"\n" +
    19. " },\n" +
    20. " {\n" +
    21. " \"title\":\"当前状态\",\n" +
    22. " \"field\":\"CURRENT_STATUS\"\n" +
    23. " }\n" +
    24. " ]\n" +
    25. " ]\n" +
    26. " }";
    27. Map headerMap = JSON.parseObject(jsonString);
    28. List> list = new ArrayList<>();
    29. for (int i = 1; i < 65534; i++) {
    30. Map map = new HashMap<>();
    31. map.put("SEQ", "seq" + i);
    32. map.put("CURRENT_STATUS", "CURRENT_STATUS" + i);
    33. list.add(map);
    34. }
    35. HSSFWorkbook workbook = TestController.test03(headerMap, list);
    36. FileOutputStream os = new FileOutputStream("E:\\\\测试POI生成文件\\测试poi生成文件03.xls");
    37. workbook.write(os);
    38. }

    2.响应式导出Excel

    1. /**
    2. *
    3. * @param head 列表标题行,例:{"head": {"title": "接口异常统计数据","columns": [[{"title": "接口名称","field": "requestUrl"}, {"title": "接口类型","field": "interfaceType"}]]}}
    4. * @param param 查询列表数据参数 {"code":"c_test_select","initSql":"AA==","init":[],"query":[{"name":"XM","value":"","type":"2"}]}
    5. * @param request
    6. * @param response
    7. * @return
    8. * @throws Exception
    9. */
    10. @ApiOperation("2.导出列表数据")
    11. @GetMapping(value = "exportQueryData")
    12. public void exportQueryExcel(@RequestParam(value = "head") String head,
    13. @RequestParam(value = "param" ) String param,
    14. @RequestParam(value = "pager.pageNo" , defaultValue = "1") String pageNo,
    15. @RequestParam(value = "pager.pageSize" , defaultValue = "0") String pageSize,
    16. @RequestParam(value = "sort" , defaultValue = "") String sort,
    17. @RequestParam(value = "direction" , defaultValue = "") String direction,
    18. HttpServletRequest request,
    19. HttpServletResponse response) throws Exception{
    20. queryService.exportQueryExcel(head, param, pageNo, pageSize, sort, direction, request, response);
    21. /**
    22. *
    23. * @param head 列表标题行,例:{"head": {"title": "接口异常统计数据","columns": [[{"title": "接口名称","field": "requestUrl"}, {"title": "接口类型","field": "interfaceType"}]]}}
    24. * @param param 查询列表数据参数 {"code":"c_test_select","initSql":"AA==","init":[],"query":[{"name":"XM","value":"","type":"2"}]}
    25. * @param request
    26. * @param response
    27. * @return
    28. * @throws Exception
    29. */
    30. void exportQueryExcel(String head, String param, String pageNo, String pageSize, String sort, String direction, HttpServletRequest request, HttpServletResponse response) throws Exception;
    31. @Override
    32. public void exportQueryExcel(String head, String param, String pageNo, String pageSize, String sort, String direction, HttpServletRequest request, HttpServletResponse response) throws Exception {
    33. log.info("-------------------------------开始导出数据------------------------------------------------------");
    34. String deStringParam = ""; // 解密后 param
    35. String deStringHead = ""; // 解密后 head
    36. try {
    37. // 解密(前端加密2次,)
    38. deStringParam = URLDecoder.decode(param, "UTF-8");
    39. log.info("解密后param:" + deStringParam);
    40. deStringHead = URLDecoder.decode(head, "UTF-8");
    41. log.info("解密后head:" + deStringHead);
    42. }catch (Exception e){
    43. log.error("解密数据异常");
    44. e.printStackTrace();
    45. }
    46. Map paramMap = JSON.parseObject(deStringParam, Map.class);
    47. Map headMap = new HashMap<>();
    48. List outTitleAndColumnsList = new ArrayList<>();
    49. List> inTitleAndColumnsList = new ArrayList<>();
    50. String fileTitle = "";
    51. if (paramMap!= null){
    52. // 获取列表的查询标识
    53. String queryCode = (String)paramMap.get("code");
    54. Query query = queryDao.get(queryCode);
    55. // 导出文件的标题
    56. fileTitle = query.getQueryName();
    57. String[] codes = new String[]{queryCode};
    58. List fList = queryDao.getField(codes);
    59. // 获取到导出文件的表头
    60. for (Field field : fList) {
    61. // List fieldList = new ArrayList();
    62. String[] inSort = deStringHead.split(",");
    63. for (String inS : inSort) {
    64. String fieSort = String.valueOf(field.getSort().toString());
    65. if (fieSort.equals(inS)){
    66. Map fieldMap = new HashMap<>();
    67. String tittle = field.getTittle();
    68. String fieldName = field.getFieldName();
    69. fieldMap.put("title", tittle);
    70. fieldMap.put("field", fieldName);
    71. inTitleAndColumnsList.add(fieldMap);
    72. }
    73. }
    74. }
    75. }
    76. // List nullList = new ArrayList<>();
    77. // nullList.add(inTitleAndColumnsList);
    78. // outTitleAndColumnsList.add(nullList);
    79. outTitleAndColumnsList.add(inTitleAndColumnsList);
    80. Map map = new HashMap();
    81. map.put("title", fileTitle);
    82. map.put("columns", outTitleAndColumnsList);
    83. headMap.put("head",map);
    84. deStringHead = JSON.toJSONString(headMap);
    85. log.info("-----------------------------------" + deStringHead);
    86. // 获取需要导出的数据
    87. Map inVo = new HashMap<>();
    88. inVo.put("param", deStringParam);
    89. inVo.put("pager.pageNo", pageNo);
    90. // 暂时限制最多导出 1w 条数据
    91. inVo.put("pager.pageSize", (StringUtils.isBlank(pageSize) || Integer.valueOf(pageSize) > 10000) ? "10000" : pageSize);
    92. inVo.put("sort", sort);
    93. inVo.put("direction", direction);
    94. log.info("导出:查询数据,请求地址为:{},请求参数为:{}", commonQueryLoadDataUrl, JSON.toJSONString(inVo));
    95. String result = HttpUtils.postString(queryDataUrl, inVo);
    96. log.info("请求返回结果为:{}", result);
    97. Map resultMap = JSON.parseObject(result, Map.class);
    98. if (null == resultMap || !resultMap.containsKey("rows") || CollectionUtils.isEmpty((List)resultMap.get("rows"))){
    99. throw new Exception("未查询到数据,请稍后再试!");
    100. }
    101. // 列表数据 集合(需要导出的数据)
    102. List rows = (List)resultMap.get("rows");
    103. List> dataList = ExportUtils.formatList(rows);
    104. log.info("导出数据量为" + dataList.size());
    105. Map parameterMap = new HashMap();
    106. parameterMap.put("map",deStringParam);
    107. Map headerMap = ExportUtils.buildMap(deStringHead,"head");// 列表标题行
    108. // Excel的head 和 查询到的数据字段名会不一致,将导出的Excel的head名转换为数据字段名
    109. if (!CollectionUtils.isEmpty(dataList)){
    110. Map dataMap = dataList.get(0); // 数据的字段名 值
    111. List> columns = (List>)((List) headerMap.get("columns")).get(0); // 传入的需要导出的标题 字段名
    112. for (String key : dataMap.keySet()) {
    113. for (Map columnsMap : columns){
    114. if (key.equalsIgnoreCase(columnsMap.get("field"))){
    115. columnsMap.put("field", key);
    116. }
    117. }
    118. }
    119. }
    120. //生成数据
    121. HSSFWorkbook workbook = ExportUtils.createExcel(headerMap, dataList);
    122. //输出
    123. Writer.exportExcel(response, workbook, ExportUtils.getTitle(headerMap));
    124. log.info("-------------------------------结束导出数据------------------------------------------------------");
    125. }

    3.ExportUtils工具类

    1. import com.alibaba.fastjson.JSON;
    2. import net.sf.json.JSONObject;
    3. import org.apache.commons.lang.StringUtils;
    4. import org.apache.poi.hssf.usermodel.*;
    5. import org.apache.poi.hssf.util.Region;
    6. import javax.servlet.http.HttpServletResponse;
    7. import java.util.ArrayList;
    8. import java.util.HashMap;
    9. import java.util.List;
    10. import java.util.Map;
    11. import java.util.regex.Pattern;
    12. public class ExportUtils {
    13. // 通用Excel导出
    14. public static HSSFWorkbook createExcel(Map headerMap,
    15. List> dataList) {
    16. // 第三行开始写表头
    17. int headNum = 2;
    18. // 表头行数
    19. int headSize = 0;
    20. // 数据列数
    21. int columnLength = 0;
    22. int[][] place = null;
    23. String[] field = null;
    24. List dataField = new ArrayList();
    25. // 创建excel工作簿
    26. HSSFWorkbook workbook = new HSSFWorkbook();
    27. // 创建sheet
    28. HSSFSheet sheet = workbook.createSheet();
    29. // 单元格样式
    30. HSSFCellStyle style = workbook.createCellStyle(); // 样式对象
    31. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直
    32. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
    33. // 字体样式
    34. HSSFFont font = workbook.createFont();
    35. font.setFontHeightInPoints((short) 20);// 设置字体大小
    36. style.setFont(font);
    37. // 单元格样式
    38. HSSFCellStyle cellStyle = workbook.createCellStyle(); // 样式对象
    39. cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直
    40. cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
    41. HSSFRow row1 = sheet.createRow(0);
    42. row1.setHeight((short) 500);
    43. HSSFCell cell1 = row1.createCell((short) 0);
    44. //sheet.addMergedRegion(new Region(0, (short) 0, 1, (short) 10));
    45. cell1.setCellStyle(style);
    46. //-------------cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
    47. // 写Excel文件名称
    48. cell1.setCellValue(headerMap.get("title").toString());
    49. // 获取表头数据
    50. List> headerList = (List>) headerMap
    51. .get("columns");
    52. headSize = headerList.size();
    53. // 通过第一列表头,获取导出Excel列数
    54. List> first = (List>) headerList
    55. .get(0);
    56. for (int i = 0; i < first.size(); i++) {
    57. Map m = first.get(i);
    58. if (null != m.get("colspan")) {
    59. Object value = m.get("colspan");
    60. if (value instanceof Integer) {
    61. columnLength = columnLength + (Integer) value;
    62. }
    63. } else {
    64. columnLength = columnLength + 1;
    65. }
    66. }
    67. // 初始化表头位置标志,用于判断单元格是否合并
    68. place = new int[headSize][columnLength];
    69. field = new String[columnLength];
    70. System.out.println(" columnLength " + columnLength);
    71. System.out.println(" headsize " + headSize);
    72. // 在第三行开始创建表头
    73. HSSFRow row = sheet.createRow(headNum);
    74. // 设置每一列的宽度
    75. sheet.setDefaultColumnWidth((short) 15);
    76. sheet.addMergedRegion(new Region(0, (short) 0, 1, (short) (columnLength-1)));
    77. for (int i = 0; i < headerList.size(); i++) {
    78. if (headerList.get(i) instanceof List) {
    79. int k = 0, l = 0;
    80. // 获取当前行的表头设置
    81. List> header = (List>) headerList
    82. .get(i);
    83. for (; k < columnLength; k++) {
    84. HSSFCell cellCheck = null;
    85. HSSFCell cell = null;
    86. int rowspan = 0;
    87. int colspan = 0;
    88. // 合并单元格直接跳过,进入下一列
    89. if (place[headNum - 2][k] == 1) {
    90. continue;
    91. } else { // 否则创建单元格
    92. cell = row.createCell((short) k);
    93. }
    94. // 获取当前单元格定义
    95. Map h = header.get(l);
    96. // 获取跨行
    97. if (null != h.get("rowspan")) {
    98. Object value = h.get("rowspan");
    99. if (value instanceof Integer) {
    100. rowspan = (Integer) value;
    101. }
    102. }
    103. // 获取跨列
    104. if (null != h.get("colspan")) {
    105. Object value = h.get("colspan");
    106. if (value instanceof Integer) {
    107. colspan = (Integer) value;
    108. }
    109. }
    110. if (rowspan != 0 && colspan != 0) { // 跨行跨列
    111. // 合并单元格
    112. sheet.addMergedRegion(new Region(headNum, (short) k,
    113. headNum + rowspan - 1,
    114. (short) (k + colspan - 1)));
    115. // 标记合并单元格
    116. for (int m = headNum; m < headNum + rowspan; m++) {
    117. for (int n = k; n < k + colspan; n++) {
    118. place[m - 2][n] = 1;
    119. }
    120. }
    121. k = k + colspan - 1;
    122. } else if (rowspan != 0) { // 只跨行
    123. // 合并单元格
    124. sheet.addMergedRegion(new Region(headNum, (short) k,
    125. headNum + rowspan - 1, (short) k));
    126. // 标记合并单元格
    127. for (int m = headNum; m < headNum + rowspan; m++) {
    128. place[m - 2][k] = 1;
    129. }
    130. } else if (colspan != 0) { // 只跨列
    131. // 合并单元格
    132. sheet.addMergedRegion(new Region(headNum, (short) k,
    133. headNum, (short) (k + colspan - 1)));
    134. // 标记合并单元格
    135. for (int n = k; n < k + colspan; n++) {
    136. place[headNum - 2][n] = 1;
    137. }
    138. // 标记下一个未写列
    139. k = k + colspan - 1;
    140. }
    141. // 下一个表头设置
    142. l++;
    143. // 标记字段值
    144. if (null != h.get("field")
    145. && StringUtils.isNotBlank(h.get("field"))) {
    146. field[k] = h.get("field");
    147. dataField.add(h.get("field"));
    148. }
    149. // 设置单元格的样式
    150. cell.setCellStyle(cellStyle);
    151. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    152. //-------------cell.setEncoding(HSSFCell.ENCODING_UTF_16);
    153. // 在单元格写内容
    154. cell.setCellValue(h.get("title").toString());
    155. cell.getStringCellValue();
    156. }
    157. // 下一行
    158. headNum = headNum + 1;
    159. row = sheet.createRow(headNum);
    160. }
    161. }
    162. for (int i = 0; i < dataList.size(); i++) {
    163. // 表头的下一行开始填充数据
    164. HSSFRow row_value = sheet.createRow(headNum);
    165. Map dataMap = dataList.get(i);
    166. // System.out.println("------------------start数据"+ i + 1 +"------------------");
    167. // String string = JSON.toJSONString(dataMap);
    168. // System.out.println(string);
    169. // System.out.println("------------------end数据"+ i + 1 +"------------------");
    170. for (int n = 0; n < field.length; n++) {
    171. // if (dataMap.get("CUST_CER_ID").equals("2134の1") && n == 9){
    172. // System.out.println(1111);
    173. // Object cust_cer_id = dataMap.get("CUST_CER_ID");
    174. // System.out.println(cust_cer_id);
    175. // }
    176. HSSFCell cell = row_value.createCell((short) n);
    177. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    178. //-------------cell.setEncoding(HSSFCell.ENCODING_UTF_16);
    179. // cell.setCellValue(dataMap.get(field[n]) == null ? ""
    180. // : dataMap.get(field[n]).toString());
    181. if(dataMap.get(field[n]) == null || dataMap.get(field[n]).toString() == ""){
    182. cell.setCellValue("");
    183. }else{
    184. Boolean strResult = dataMap.get(field[n]).toString().matches("-[0-9]+(.[0-9]+)?|[0-9]+(.[0-9]+)?");
    185. Pattern p = Pattern.compile("[a-zA-z]");
    186. /**判断是否含有英文单词*/
    187. Boolean flag = p.matcher(dataMap.get(field[n]).toString()).find();
    188. /**dataMap.get(field[n]).toString().indexOf("-")>0判断主要是区分字符串2017-10和数字-10*/
    189. // if (!strResult||dataMap.get(field[n]).toString().indexOf("-")>0||flag){
    190. // cell.setCellValue(dataMap.get(field[n]).toString());
    191. // }else{
    192. // if(dataMap.get(field[n]).toString().length()>11){
    193. // //韶关现场 事项编码数字过长,导出时转换为String类型
    194. // cell.setCellValue(dataMap.get(field[n]).toString());
    195. // }else{
    196. // // 存在特殊符号的时候转换成 Double类型会出错
    197. // cell.setCellValue(Double.parseDouble(dataMap.get(field[n]).toString()));
    198. // }
    199. // }
    200. cell.setCellValue(dataMap.get(field[n]).toString());
    201. }
    202. }
    203. headNum = headNum + 1;
    204. }
    205. return workbook;
    206. }
    207. /**
    208. * 根据前台参数 整理出表头数据
    209. * @param parameterMap
    210. * @return
    211. */
    212. public static Map buildMap(Map parameterMap, String key){
    213. JSONObject json = JSONObject.fromObject(parameterMap.get("map"));
    214. Map param = json;
    215. if (key!=null) {
    216. Map keyMap = (Map) param.get(key);
    217. return keyMap;
    218. }
    219. // 获取表头数据
    220. return param;
    221. }
    222. /**
    223. * 根据前台参数 整理出表头数据
    224. * @param parameterMap json串
    225. * @param key head
    226. * @return
    227. */
    228. public static Map buildMap(String parameterMap, String key){
    229. Map param = JSON.parseObject(parameterMap, Map.class);
    230. // Map param = json;
    231. if (key!=null) {
    232. Map keyMap = (Map) param.get(key);
    233. return keyMap;
    234. }
    235. // 获取表头数据
    236. return param;
    237. }
    238. public static Map buildHeadMap(Map parameterMap){
    239. Map keyMap = (Map) parameterMap.get("head");
    240. return keyMap;
    241. }
    242. /**
    243. * 获取一个title
    244. * @param headerMap
    245. * @return
    246. */
    247. public static String getTitle(Map headerMap){
    248. return headerMap.get("title") == null ? "未命名" : headerMap.get("title").toString();
    249. }
    250. /**
    251. * 根据 list 生成 List> 格式的数据
    252. * @param
    253. * @param list
    254. * @return
    255. */
    256. @SuppressWarnings("unchecked")
    257. public static List> formatList(List list){
    258. List> dataList = new ArrayList>();
    259. for(Object temp:list){
    260. dataList.add(JSONObject.fromObject(temp));
    261. }
    262. return dataList;
    263. }
    264. /**
    265. * 传进表头数据和列表数据 直接导出excel
    266. * @param header
    267. * @param list
    268. * @param response
    269. */
    270. public static void exportWrite(String header, List list, HttpServletResponse response){
    271. Map parameterMap = new HashMap();
    272. parameterMap.put("map", header);
    273. List> dataList = formatList(list);
    274. //根据head生成表头数据
    275. Map headerMap = buildMap(parameterMap,"head");
    276. //生成数据
    277. HSSFWorkbook workbook = createExcel(headerMap,dataList);
    278. //输出
    279. Writer.exportExcel(response, workbook, getTitle(headerMap));
    280. }
    281. }
    282. 4.Writer工具类

      1. import net.sf.json.JSONArray;
      2. import net.sf.json.JSONObject;
      3. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
      4. import javax.servlet.http.HttpServletResponse;
      5. import java.io.IOException;
      6. import java.io.OutputStream;
      7. import java.io.PrintWriter;
      8. import java.net.URLEncoder;
      9. import java.util.List;
      10. import java.util.Map;
      11. /**
      12. * 文件名称:Writer.java
      13. *
      14. *
      15. */
      16. public class Writer {
      17. /**
      18. * 输出不分页列表到前台
      19. * @param response
      20. * @param list
      21. */
      22. public static void outPutList(HttpServletResponse response, List list){
      23. try {
      24. response.setContentType("text/html;charset=GBK");
      25. PrintWriter out = response.getWriter();
      26. out.print(JSONArray.fromObject(list));
      27. out.flush();
      28. out.close();
      29. } catch (IOException e) {
      30. e.printStackTrace();
      31. }
      32. }
      33. /**
      34. * 输出普通对象到前台
      35. * @param response
      36. * @param list
      37. */
      38. public static void outPutObject(HttpServletResponse response, Object object){
      39. try {
      40. response.setContentType("text/html;charset=GBK");
      41. PrintWriter out = response.getWriter();
      42. out.print(JSONObject.fromObject(object));
      43. out.flush();
      44. out.close();
      45. } catch (IOException e) {
      46. e.printStackTrace();
      47. }
      48. }
      49. /**
      50. * 输出字符串到前台
      51. * @param response
      52. * @param list
      53. */
      54. public static void outPutStr(HttpServletResponse response, String jsonStr){
      55. try {
      56. response.setContentType("text/html;charset=GBK");
      57. PrintWriter out = response.getWriter();
      58. out.print(jsonStr);
      59. out.flush();
      60. out.close();
      61. } catch (IOException e) {
      62. e.printStackTrace();
      63. }
      64. }
      65. /**
      66. * 导出到excel
      67. * @param response
      68. * @param workbook
      69. */
      70. public static void exportExcel(HttpServletResponse response, HSSFWorkbook workbook ){
      71. try{
      72. OutputStream out = response.getOutputStream();;
      73. response.setContentType("application/vnd.ms-excel;charset=utf-8");
      74. response.setCharacterEncoding("utf-8");
      75. response.setHeader("Content-disposition", "attachment; filename="
      76. // + new String("所有办件统计".getBytes("utf-8"), "ISO8859-1")+".xls");
      77. + String.valueOf(URLEncoder.encode("所有办件统计", "UTF-8"))+".xls");
      78. workbook.write(out);
      79. out.flush();
      80. out.close();
      81. }catch(Exception e){
      82. e.printStackTrace();
      83. }
      84. }
      85. /**
      86. * 导出到excel,文件名可自定义
      87. * @param response
      88. * @param workbook
      89. */
      90. public static void exportExcel(HttpServletResponse response, HSSFWorkbook workbook, String fileName ){
      91. try{
      92. OutputStream out = response.getOutputStream();;
      93. response.setContentType("application/vnd.ms-excel;charset=utf-8");
      94. response.setCharacterEncoding("utf-8");
      95. /*response.setHeader("Content-disposition", "attachment; filename="
      96. + String.valueOf(URLEncoder.encode(fileName, "UTF-8"))+".xls");*/
      97. /**ISO8859-1是页面上数据传输的格式*/
      98. response.addHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("GB2312"),"ISO-8859-1")+".xls");
      99. workbook.write(out);
      100. out.flush();
      101. out.close();
      102. }catch(Exception e){
      103. e.printStackTrace();
      104. }
      105. }
      106. /**
      107. * 输出分页列表到前台供datagrid使用
      108. * @param response
      109. * @param list
      110. */
      111. public static void outPutToDataGrid(HttpServletResponse response, List> list){
      112. try {
      113. response.setContentType("text/html;charset=GBK");
      114. PrintWriter out = response.getWriter();
      115. DataGridObject dg = new DataGridObject();
      116. dg.setRows(list);
      117. dg.setTotal(PagerThreadLocal.getValue().getTotal()==0?list.size():PagerThreadLocal.getValue().getTotal());
      118. JSONObject jsonObject = JSONObject.fromObject(dg);
      119. out.print(jsonObject.toString());
      120. out.flush();
      121. out.close();
      122. } catch (IOException e) {
      123. e.printStackTrace();
      124. }
      125. }
      126. }

      二、解析加密数据再导出

      2.1 ExcelUtil工具类:

      1. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
      2. import org.apache.poi.ss.usermodel.*;
      3. import java.io.FileInputStream;
      4. import java.io.FileOutputStream;
      5. import java.io.IOException;
      6. import java.lang.reflect.Field;
      7. import java.util.ArrayList;
      8. import java.util.List;
      9. /**
      10. * 借鉴地址:https://blog.csdn.net/qq_37960007/article/details/84451534?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-14.control&dist_request_id=1328593.13383.16147799212719547&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-14.control
      11. * java如何读取、写入Excel文件(将内容转成任意的bean对象)
      12. */
      13. public class ExcelUtil {
      14. public static List parseFromExcel(String path, Class aimClass) {
      15. return parseFromExcel(path, 0, aimClass);
      16. }
      17. /**
      18. * 导入Excel文件,将其数据装换为对应实体bean
      19. * @param path 文件路径
      20. * @param firstIndex 从firstIndex行开始
      21. * @param aimClass 对应的实体类
      22. * @param
      23. * @return
      24. */
      25. @SuppressWarnings("deprecation")
      26. public static List parseFromExcel(String path, int firstIndex, Class aimClass) {
      27. List result = new ArrayList();
      28. try {
      29. FileInputStream fis = new FileInputStream(path);
      30. Workbook workbook = WorkbookFactory.create(fis);
      31. //对excel文档的第一页,即sheet1进行操作
      32. Sheet sheet = workbook.getSheetAt(0);
      33. int lastRaw = sheet.getLastRowNum();
      34. for (int i = firstIndex; i <= lastRaw; i++) {
      35. //第i行
      36. Row row = sheet.getRow(i);
      37. T parseObject = aimClass.newInstance();
      38. Field[] fields = aimClass.getDeclaredFields();
      39. for (int j = 0; j < fields.length; j++) {
      40. Field field = fields[j];
      41. field.setAccessible(true);
      42. Class type = field.getType();
      43. //第j列
      44. Cell cell = row.getCell(j);
      45. if (cell == null)
      46. continue;
      47. //很重要的一行代码,如果不加,像12345这样的数字是不会给你转成String的,只会给你转成double,而且会导致cell.getStringCellValue()报错
      48. cell.setCellType(Cell.CELL_TYPE_STRING);
      49. String cellContent = cell.getStringCellValue();
      50. cellContent = "".equals(cellContent) ? "0" : cellContent;
      51. if (type.equals(String.class)) {
      52. field.set(parseObject, cellContent);
      53. } else if (type.equals(char.class) || type.equals(Character.class)) {
      54. field.set(parseObject, cellContent.charAt(0));
      55. } else if (type.equals(int.class) || type.equals(Integer.class)) {
      56. field.set(parseObject, Integer.parseInt(cellContent));
      57. } else if (type.equals(long.class) || type.equals(Long.class)) {
      58. field.set(parseObject, Long.parseLong(cellContent));
      59. } else if (type.equals(float.class) || type.equals(Float.class)) {
      60. field.set(parseObject, Float.parseFloat(cellContent));
      61. } else if (type.equals(double.class) || type.equals(Double.class)) {
      62. field.set(parseObject, Double.parseDouble(cellContent));
      63. } else if (type.equals(short.class) || type.equals(Short.class)) {
      64. field.set(parseObject, Short.parseShort(cellContent));
      65. } else if (type.equals(byte.class) || type.equals(Byte.class)) {
      66. field.set(parseObject, Byte.parseByte(cellContent));
      67. } else if (type.equals(boolean.class) || type.equals(Boolean.class)) {
      68. field.set(parseObject, Boolean.parseBoolean(cellContent));
      69. }
      70. }
      71. result.add(parseObject);
      72. }
      73. fis.close();
      74. } catch (Exception e) {
      75. e.printStackTrace();
      76. System.err.println("An error occured when parsing object from Excel. at " );
      77. }
      78. return result;
      79. }
      80. // 带标题写入Excel
      81. public static void writeExcelWithTitle(List beans, String path) {
      82. writeExcel(beans,path,true);
      83. }
      84. // 仅把数据写入Excel
      85. public static void writeExcel(List beans, String path) {
      86. writeExcel(beans,path,false);
      87. }
      88. /**
      89. *
      90. * @param beans 需要写成Excel文件的集合数据
      91. * @param path 写到的指定路径
      92. * @param writeTitle 文件标题
      93. * @param
      94. */
      95. private static void writeExcel(List beans, String path, boolean writeTitle) {
      96. if(beans == null || beans.size() == 0){
      97. return;
      98. }
      99. Workbook workbook = new HSSFWorkbook();
      100. FileOutputStream fos = null;
      101. int offset = writeTitle ? 1 : 0;
      102. try {
      103. Sheet sheet = workbook.createSheet();
      104. for (int i = 0; i < beans.size() + offset; ++i) {
      105. if(writeTitle && i == 0) {
      106. createTitle(beans, sheet);
      107. continue;
      108. }
      109. Row row = sheet.createRow(i);
      110. T bean = beans.get(i - offset);
      111. Field[] fields = bean.getClass().getDeclaredFields();
      112. for (int j = 0; j < fields.length; j++) {
      113. Field field = fields[j];
      114. field.setAccessible(true);
      115. Cell cell = row.createCell(j);
      116. //Date,Calender都可以 使用 +"" 操作转成字符串
      117. cell.setCellValue(field.get(bean)+"");
      118. }
      119. }
      120. fos = new FileOutputStream(path);
      121. workbook.write(fos);
      122. } catch (Exception e) {
      123. e.printStackTrace();
      124. }finally {
      125. try {
      126. fos.close();
      127. workbook.close();
      128. } catch (IOException e) {
      129. e.printStackTrace();
      130. }
      131. }
      132. }
      133. private static void createTitle(List beans,Sheet sheet){
      134. Row row = sheet.createRow(0);
      135. T bean = beans.get(0);
      136. Field[] fields = bean.getClass().getDeclaredFields();
      137. for (int i = 0; i < fields.length; i++) {
      138. Field field = fields[i];
      139. field.setAccessible(true);
      140. Cell cell = row.createCell(i);
      141. cell.setCellValue(field.getName());
      142. }
      143. }
      144. public static void main(String[] args) {
      145. /**
      146. * 1.将Excel文件读取到程序中
      147. */
      148. //参数里的1表示有效行数从第1行开始
      149. List publicUserList = ExcelUtil.parseFromExcel("C:\\Users\\tission_01\\Desktop\\(解密前).xlsx", 1,AESPublicUser.class);
      150. System.out.println("数据量:-----------" + publicUserList.size());
      151. for (AESPublicUser aesPublicUser : publicUserList) {
      152. System.out.println(aesPublicUser.toString());
      153. }
      154. // 解密手机号码或IDcard号码
      155. EncryptDesUtils des2 = new EncryptDesUtils("TESTTESTWIJDINVA");
      156. for(AESPublicUser user : publicUserList){
      157. try {
      158. user.setCertificate_no(des2.decrypt(user.getCertificate_no()));
      159. user.setContact_phone(des2.decrypt(user.getContact_phone()));
      160. } catch (Exception e) {
      161. e.printStackTrace();
      162. }
      163. }
      164. /**
      165. * 2.将数据写成Excel文件
      166. */
      167. // // 带标题写入excel
      168. // List scenics = Lists.newArrayList();
      169. // ExcelUtil.writeExcelWithTitle(scenics,"C:\\Users\\unive\\Documents\\景点信息\\scenics.xlsx");
      170. //
      171. // // 不带标题写入excel
      172. ExcelUtil.writeExcel(publicUserList,"C:\\Users\\tission_01\\Desktop\\(解密后).xlsx");
      173. }
      174. }

      2.2 Excel 对应的 实体类:

      1. import lombok.AllArgsConstructor;
      2. import lombok.Builder;
      3. import lombok.Data;
      4. import lombok.NoArgsConstructor;
      5. @Data
      6. @Builder
      7. @NoArgsConstructor
      8. @AllArgsConstructor
      9. public class AESPublicUser {
      10. /**
      11. * 用户ID
      12. */
      13. private String user_id;
      14. /**
      15. * 用户名
      16. */
      17. // private String user_name;
      18. /**
      19. * 手机号码
      20. */
      21. private String contact_phone;
      22. /**
      23. * 证件号码
      24. */
      25. private String certificate_no;
      26. }

    283. 相关阅读:
      【RHCE】作业:DNS主从同步&防火墙iptables服务使用
      如何有效利用chatgpt?
      二、训练fashion_mnist数据集
      java-Spring-入门学习-第二天(单例模式和多例模式)
      K8s控制器
      语法基础(函数)
      python毕业设计作品基于django框架个人博客系统毕设成品(8)毕业设计论文模板
      react151618刷新几次的问题
      java,python遍历文件夹与子文件夹
      java随手记
    284. 原文地址:https://blog.csdn.net/liumangtutu2919/article/details/126450813