当前位置:   article > 正文

企微群机器人推送文本+Excel_企业微信 webhook发送表格

企业微信 webhook发送表格

例如,企微群定时推送:内容+表格

群机器人:学校基本信息:

[一个记录学校基本信息的excel表]

 excel表简单类似:

准备肯定先企微群创建一个机器人,获取到群webhook备用;

简易步骤比较简单,先分别获取老师、学生、职工的list信息->再把列表转化为excel表->推送消息

 一、推送工具类;(isNotBank之类的判空方法,可以自行重写)

  1. import lombok.extern.slf4j.Slf4j;
  2. import okhttp3.*;
  3. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  4. import java.io.File;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.concurrent.TimeUnit;
  9. /**
  10. * @author yrl
  11. * @date 2023/7/5 15:29
  12. */
  13. @Slf4j
  14. public class WxPushUtil {
  15. /**
  16. * 企业微信机器人api地址与key;webhook 截取
  17. */
  18. private final static String WECHAT_API_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/";
  19. private final static String WECHAT_API_KEY = "xxxxx-xxx-xxx-xxxxxxxxxxxxxxxxx";
  20. /**
  21. * 学生列表数据转化为 excel
  22. *
  23. * @param wb Workbook
  24. * @param student 学生
  25. * @param dest 首栏提示 默认可空
  26. * @param pageName 底部分页表名称
  27. */
  28. public static boolean studentFileBuild(HSSFWorkbook wb, List<student> student, String dest, String pageName) {
  29. //
  30. if (student == null || student.size() < 0) {
  31. return false;
  32. }
  33. //表头字段,与对象一致
  34. String[] titleArray = new String[]{"学生姓名", "年龄", "性别", "班级"};
  35. String[] fieldArray = new String[]{"studentName", "age", "sex", "class"};
  36. List<Map<String, Object>> list = new ArrayList<>();
  37. for (Student s : student) {
  38. //转成map
  39. Map<String, Object> map = BeanUtils.beanToMap(s);
  40. list.add(map);
  41. }
  42. if (list.size() > 0) {
  43. //数据组合 到HSSFWorkbook
  44. ExcelUtil.buildExcel(list, wb, pageName, titleArray, fieldArray, dest);
  45. return true;
  46. }
  47. return false;
  48. }
  49. /**
  50. * 老师 数据转化为excel构建
  51. *
  52. * @param wb Workbook
  53. * @param teacher 老师
  54. * @param dest 首栏提示 默认可空
  55. * @param pageName 底部分页表名称
  56. */
  57. public static boolean teacherFileBuild(HSSFWorkbook wb, List<Teacher> teacher, String dest, String pageName) {
  58. //
  59. if (teacher == null || teacher.size() < 0) {
  60. return false;
  61. }
  62. //表头字段,与对象一致
  63. String[] titleArray = new String[]{"工号", "姓名", "性别", "职位"};
  64. String[] fieldArray = new String[]{"number", "name", "sex", "lev"};
  65. List<Map<String, Object>> list = new ArrayList<>();
  66. for (Teacher s : teacher) {
  67. //转成map
  68. Map<String, Object> map = BeanUtils.beanToMap(s);
  69. list.add(map);
  70. }
  71. if (list.size() > 0) {
  72. //数据组合 到HSSFWorkbook
  73. ExcelUtil.buildExcel(list, wb, pageName, titleArray, fieldArray, dest);
  74. return true;
  75. }
  76. return false;
  77. }
  78. /**
  79. * 发送文件消息,需要先将文件上传到企业微信临时素材,再根据获取的media_id调用群机器人
  80. *
  81. * @param file 需要发送的文件
  82. * @param text 发送附件的同时需要发送文字内容
  83. * @param phoneList 需要@的群成员手机号
  84. */
  85. public static void sendFileMsg(File file, String text, List<String> phoneList) {
  86. // 构造RequestBody对象,用来携带要提交的数据;需要指定MediaType,用于描述请求/响应 body 的内容类型
  87. MediaType contentType = MediaType.parse("application/form-data; boundary");
  88. RequestBody body = RequestBody.create(contentType, file);
  89. RequestBody requestBody = new MultipartBody.Builder()
  90. .setType(MultipartBody.FORM)
  91. .addFormDataPart("file", file.getName(), body)
  92. .build();
  93. try {
  94. //获取推送的群id,如果多个,推送多个
  95. // 上传到临时素材
  96. String mediaUrl = WECHAT_API_URL + "upload_media?type=file&key=" + WECHAT_API_KEY;
  97. log.debug("将文件{}上传到临时素材:{}", file.getName(), mediaUrl);
  98. String respMsg = okHttp(requestBody, mediaUrl);
  99. log.debug("将文件{}上传到临时素材:{}, {}", file.getName(), mediaUrl, respMsg);
  100. // 获取临时素材id
  101. JSONObject result = JSONUtil.parseObj(respMsg);
  102. String mediaId = result.getStr("media_id");
  103. if (U.isNotBlank(text)) {
  104. JSONObject textJson = new JSONObject();
  105. textJson.set("content", text);
  106. JSONObject reqBody = new JSONObject();
  107. //先推文本
  108. reqBody.set("msgtype", "text");
  109. reqBody.set("text", textJson);
  110. //"mentioned_mobile_list":["13800001111","@all"]
  111. if (A.isNotEmpty(phoneList)) {
  112. System.out.println("推送的手机号:" + phoneList);
  113. reqBody.set("mentioned_mobile_list", phoneList);
  114. }
  115. // 调用群机器人发送消息
  116. callWeChatBot(reqBody.toString(), WECHAT_API_KEY);
  117. }
  118. JSONObject fileJson = new JSONObject();
  119. fileJson.set("media_id", mediaId);
  120. JSONObject reqBody = new JSONObject();
  121. //再推文件
  122. reqBody.set("msgtype", "file");
  123. reqBody.set("file", fileJson);
  124. reqBody.set("safe", 0);
  125. // 再调用群机器人发送文件消息
  126. callWeChatBot(reqBody.toString(), WECHAT_API_KEY);
  127. } catch (Exception e) {
  128. log.error("文件推送异常:{}", file.getName(), e);
  129. }
  130. }
  131. /**
  132. * @param body 携带需要提交的数据(后续迁移)
  133. * @param url 请求地址
  134. * @throws Exception 异常
  135. */
  136. private static String okHttp(RequestBody body, String url) throws Exception {
  137. // 构造和配置OkHttpClient
  138. OkHttpClient client = new OkHttpClient.Builder()
  139. // 设置连接超时时间
  140. .connectTimeout(10, TimeUnit.SECONDS)
  141. // 设置读取超时时间
  142. .readTimeout(20, TimeUnit.SECONDS)
  143. .build();
  144. // 构造Request对象
  145. Request request = new Request.Builder()
  146. .url(url)
  147. .post(body)
  148. // 响应消息不缓存
  149. .addHeader("cache-control", "no-cache")
  150. .build();
  151. // 构建Call对象,通过Call对象的execute()方法提交异步请求
  152. Response response = client.newCall(request).execute();
  153. // 请求结果处理
  154. assert response.body() != null;
  155. byte[] datas = response.body().bytes();
  156. return new String(datas);
  157. }
  158. /**
  159. * 调用群机器人
  160. *
  161. * @param reqBody 接口请求参数
  162. * @throws Exception 异常
  163. */
  164. private static void callWeChatBot(String reqBody, String key) throws Exception {
  165. log.debug("调用群机器人:{}", reqBody);
  166. // 构造RequestBody对象,用来携带要提交的数据;需要指定MediaType,用于描述请求/响应 body 的内容类型
  167. okhttp3.MediaType contentType = okhttp3.MediaType.parse("application/json; charset=utf-8");
  168. RequestBody body = RequestBody.create(contentType, reqBody);
  169. String botUrl = WECHAT_API_URL + "send?key=" + key;
  170. // 调用群机器人
  171. String respMsg = okHttp(body, botUrl);
  172. JSONObject result = JSONUtil.parseObj(respMsg);
  173. if ("0".equals(result.getStr("errcode"))) {
  174. log.debug("调用群机器人发送消息成功, reqBody: {}, respMsg : {}", reqBody, respMsg);
  175. } else {
  176. log.error("调用群机器人发送消息失败, reqBody: {}, respMsg : {}", reqBody, respMsg);
  177. }
  178. }
  179. }

二、EXCEL工具类(list转化等)有些方法可能用不到

  1. import org.apache.commons.lang3.StringUtils;
  2. import org.apache.poi.hssf.usermodel.*;
  3. import org.apache.poi.hssf.util.HSSFColor;
  4. import org.apache.poi.ss.usermodel.*;
  5. import org.apache.poi.ss.util.CellRangeAddress;
  6. import org.apache.poi.ss.util.CellRangeAddressList;
  7. import org.apache.poi.xssf.usermodel.XSSFCell;
  8. import org.apache.poi.xssf.usermodel.XSSFRow;
  9. import org.apache.poi.xssf.usermodel.XSSFSheet;
  10. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  11. import org.springframework.web.multipart.MultipartFile;
  12. import java.io.IOException;
  13. import java.lang.reflect.Field;
  14. import java.math.BigDecimal;
  15. import java.text.NumberFormat;
  16. import java.text.SimpleDateFormat;
  17. import java.time.LocalDate;
  18. import java.time.LocalDateTime;
  19. import java.time.format.DateTimeFormatter;
  20. import java.util.*;
  21. /**
  22. * Excel工具类
  23. */
  24. public class ExcelUtil<T> {
  25. public Class<T> clazz;
  26. public ExcelUtil(Class<T> clazz) {
  27. this.clazz = clazz;
  28. }
  29. /**
  30. * 读取Excel内容转为List
  31. */
  32. public List<T> importExcel(MultipartFile file) throws Exception {
  33. return importExcel(StringUtils.EMPTY, file);
  34. }
  35. /**
  36. * 读取Excel内容转为List
  37. */
  38. public List<T> importExcel(String sheetName, MultipartFile file) throws Exception {
  39. U.assertException(U.isBlank(file), "上传的文件为空");
  40. //获取文件名
  41. String fileName = file.getOriginalFilename();
  42. U.assertException(!(fileName.endsWith(".xls") || fileName.endsWith(".xlsx")), "请选择Excel文件上传");
  43. //
  44. List<T> list = new ArrayList<>();
  45. Workbook workbook = WorkbookFactory.create(file.getInputStream());
  46. Sheet sheet;
  47. if (StringUtils.isNotEmpty(sheetName)) {
  48. // 如果指定sheet名,则取指定sheet中的内容.
  49. sheet = workbook.getSheet(sheetName);
  50. } else {
  51. // 如果传入的sheet名不存在则默认指向第1个sheet.
  52. sheet = workbook.getSheetAt(0);
  53. }
  54. if (sheet == null) {
  55. throw new IOException("文件sheet不存在");
  56. }
  57. //获取数据
  58. int rows = sheet.getLastRowNum();
  59. if (rows == 0) {
  60. U.assertException("当前工作簿没数据");
  61. }
  62. //行号从0开始,所以需要+1
  63. rows = rows + 1;
  64. // 默认序号
  65. int serialNum = 0;
  66. // 有数据时才处理 得到类的所有field.
  67. Field[] allFields = clazz.getDeclaredFields();
  68. //用于校验是否存在某些字段
  69. Map<String, Field> fieldNameMap = new HashMap<>();
  70. // 定义一个map用于存放列的序号和field.
  71. Map<Integer, Field> fieldsMap = new HashMap<>();
  72. for (Field field : allFields) {
  73. // 设置类的私有字段属性可访问.
  74. field.setAccessible(true);
  75. fieldsMap.put(++serialNum, field);
  76. fieldNameMap.put(field.getName(), field);
  77. }
  78. //
  79. DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DateFormatType.YYYY_MM_DD_HH_MM_SS.getValue());
  80. DateTimeFormatter df = DateTimeFormatter.ofPattern(DateFormatType.YYYY_MM_DD.getValue());
  81. SimpleDateFormat sdf = new SimpleDateFormat(DateFormatType.YYYY_MM_DD_HH_MM_SS.getValue());
  82. //
  83. Row row = null;
  84. Cell cell = null;
  85. try {
  86. // 从第2行开始取数据,默认第一行是表头.
  87. for (int i = 1; i < rows; i++) {
  88. row = sheet.getRow(i);
  89. if (row == null) {
  90. continue;
  91. }
  92. T entity = clazz.newInstance();
  93. for (int j = 0; j < serialNum; j++) {
  94. cell = row.getCell(j);
  95. if (cell == null) {
  96. continue;
  97. }
  98. // 从map中得到对应列的field.
  99. Field field = fieldsMap.get(j + 1);
  100. // 取得类型,并根据对象类型设置值.
  101. Class<?> fieldType = field.getType();
  102. String c;
  103. //excel数字精度问题:如果是数字类型,转化
  104. if (cell.getCellTypeEnum().equals(CellType.NUMERIC) && fieldType != Date.class) {
  105. NumberFormat numberFormat = NumberFormat.getNumberInstance();
  106. double d = cell.getNumericCellValue();
  107. // 关键在这里!
  108. c = numberFormat.format(d);
  109. } else {
  110. // 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了(这里数字类型 c可能存在精度问题)
  111. cell.setCellType(CellType.STRING);
  112. c = cell.getStringCellValue();
  113. }
  114. if (StringUtils.isEmpty(c)) {
  115. continue;
  116. }
  117. if (String.class == fieldType) {
  118. field.set(entity, c);
  119. } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
  120. field.set(entity, Integer.parseInt(c));
  121. } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
  122. field.set(entity, Long.valueOf(c));
  123. } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
  124. field.set(entity, Float.valueOf(c));
  125. } else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
  126. field.set(entity, Short.valueOf(c));
  127. } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
  128. field.set(entity, Double.valueOf(c));
  129. } else if (Character.TYPE == fieldType) {
  130. if (c.length() > 0) {
  131. field.set(entity, c.charAt(0));
  132. }
  133. } else if (Date.class == fieldType) {
  134. if (cell.getCellTypeEnum() == CellType.NUMERIC) {
  135. cell.setCellValue(sdf.format(cell.getNumericCellValue()));
  136. c = sdf.format(cell.getNumericCellValue());
  137. } else {
  138. c = cell.getStringCellValue();
  139. }
  140. } else if (BigDecimal.class == fieldType) {
  141. try {
  142. field.set(entity, NumberUtil.toBigDecimal(c));
  143. } catch (Exception ex) {
  144. U.assertException("数值类型转换失败,请检查单元格值是否符合规范");
  145. }
  146. } else if (LocalDateTime.class == fieldType) {
  147. field.set(entity, LocalDateTime.parse(excelDoubleToDate(c, DateFormatType.YYYY_MM_DD_HH_MM_SS), dtf));
  148. } else if (LocalDate.class == fieldType) {
  149. field.set(entity, LocalDate.parse(excelDoubleToDate(c, DateFormatType.YYYY_MM_DD), df));
  150. }
  151. }
  152. if (BeanUtil.isNotEmpty(entity)) {
  153. //判断是否有行号字段,有的话赋值
  154. if (fieldNameMap.containsKey("rowNum")) {
  155. //记录一下行数
  156. fieldNameMap.get("rowNum").set(entity, row.getRowNum() + 1);
  157. }
  158. list.add(entity);
  159. }
  160. }
  161. } catch (Exception ex) {
  162. ex.printStackTrace();
  163. U.assertException(StrUtil.format("解析第{}行,第{}列时出错,错误原因:{}",
  164. row == null ? "null" : row.getRowNum() + 1,
  165. cell == null ? "null" : cell.getColumnIndex() + 1,
  166. ex.getMessage()));
  167. }
  168. return list;
  169. }
  170. //解析Excel日期格式
  171. public static String excelDoubleToDate(String strDate, DateFormatType dateFormatType) {
  172. try {
  173. SimpleDateFormat sdf = new SimpleDateFormat(dateFormatType.getValue());
  174. Date tDate = doubleToDate(Double.parseDouble(strDate));
  175. return sdf.format(tDate);
  176. } catch (Exception e) {
  177. //e.printStackTrace();
  178. return strDate;
  179. }
  180. }
  181. //解析Excel日期格式
  182. public static Date doubleToDate(Double dVal) {
  183. Date tDate = new Date();
  184. long localOffset = tDate.getTimezoneOffset() * 60000; //系统时区偏移 1900/1/1 到 1970/1/1 的 25569 天
  185. tDate.setTime((long) ((dVal - 25569) * 24 * 3600 * 1000 + localOffset));
  186. return tDate;
  187. }
  188. /**
  189. * 常规字体-微软雅黑-12号
  190. */
  191. public static HSSFFont getFont(HSSFWorkbook wb) {
  192. HSSFFont font = wb.createFont();
  193. font.setFontHeightInPoints((short) 12);//设置字体大小
  194. font.setFontName("微软雅黑");
  195. return font;
  196. }
  197. /**
  198. * 白色字体-微软雅黑-12号
  199. */
  200. public static HSSFFont getWhiteFont(HSSFWorkbook wb) {
  201. HSSFFont font = wb.createFont();
  202. font.setFontHeightInPoints((short) 12);//设置字体大小
  203. font.setFontName("微软雅黑");
  204. font.setColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
  205. font.setBold(true);
  206. return font;
  207. }
  208. /**
  209. * 标题字体-微软雅黑-12号-加粗
  210. */
  211. public static HSSFFont getTitleFont(HSSFWorkbook wb) {
  212. HSSFFont font = getFont(wb);
  213. font.setBold(true);
  214. return font;
  215. }
  216. /**
  217. * 常规字体-微软雅黑-12号-红色
  218. */
  219. public static HSSFFont getRedFont(HSSFWorkbook wb) {
  220. HSSFFont font = getFont(wb);
  221. font.setColor(Font.COLOR_RED);
  222. return font;
  223. }
  224. /**
  225. * 单元格样式-自动换行-全边框-左右垂直居中
  226. */
  227. public static CellStyle getCellStyle(HSSFWorkbook wb, HSSFFont font) {
  228. CellStyle style = wb.createCellStyle();//新建样式对象
  229. style.setWrapText(true);//设置自动换行
  230. style.setAlignment(HorizontalAlignment.CENTER);//居中
  231. style.setVerticalAlignment(VerticalAlignment.CENTER);//居中
  232. style.setBorderBottom(BorderStyle.THIN);//下边框
  233. style.setBorderLeft(BorderStyle.THIN);//左边框
  234. style.setBorderRight(BorderStyle.THIN);//右边框
  235. style.setBorderTop(BorderStyle.THIN);//上边框
  236. style.setFont(font);
  237. return style;
  238. }
  239. /**
  240. * 单元格样式-自动换行-全边框-左右垂直居中-背景颜色
  241. */
  242. public static CellStyle getCellStyle(HSSFWorkbook wb, HSSFFont font, short bg) {
  243. CellStyle style = getCellStyle(wb, font);
  244. //设置背景色
  245. style.setFillForegroundColor(bg);
  246. //设置填充样式
  247. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  248. return style;
  249. }
  250. /**
  251. * 设置下拉框(注意单元格内的字符不能超过255)
  252. *
  253. * @param sheet 指定sheet页
  254. * @param values 下拉框的值
  255. * @param firstRow 起始行号
  256. * @param lastRow 起始行号
  257. * @param firstCol 起始列号
  258. * @param lastCol 终止列号
  259. */
  260. public static void setDropDownBox(HSSFSheet sheet, String[] values, Integer firstRow, Integer lastRow, Integer firstCol, Integer lastCol) {
  261. // 加载下拉列表内容
  262. DVConstraint constraint = DVConstraint.createExplicitListConstraint(values);
  263. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  264. CellRangeAddressList regions = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
  265. // 数据有效性对象
  266. HSSFDataValidation data_validation_list = new HSSFDataValidation(regions, constraint);
  267. sheet.addValidationData(data_validation_list);
  268. }
  269. /**
  270. * sheet合并, 合并后删除数据源sheet
  271. *
  272. * @param workbook
  273. * @param sourceSheet 数据源
  274. * @param targetSheet 合并到
  275. * @return
  276. * @throws IOException
  277. */
  278. public static void mergeSheet(XSSFWorkbook workbook, int sourceSheet, int targetSheet) throws IOException {
  279. final XSSFSheet target = workbook.getSheetAt(targetSheet);
  280. final XSSFSheet source = workbook.getSheetAt(sourceSheet);
  281. int lastRowNum = target.getLastRowNum();
  282. final List<CellRangeAddress> mergedRegions = source.getMergedRegions();
  283. //处理合并后的mergedRegion
  284. for (CellRangeAddress mergedRegion : mergedRegions) {
  285. mergedRegion.setFirstRow(mergedRegion.getFirstRow() + lastRowNum + 1);
  286. mergedRegion.setLastRow(mergedRegion.getLastRow() + lastRowNum + 1);
  287. }
  288. //逐行复制
  289. for (int i = 0; i <= source.getLastRowNum(); i++) {
  290. final XSSFRow row = source.getRow(i);
  291. if (row == null) {
  292. target.createRow(++lastRowNum);
  293. continue;
  294. }
  295. final Iterator<Cell> cellIterator = row.cellIterator();
  296. final XSSFRow s1Row = target.createRow(++lastRowNum);
  297. while (cellIterator.hasNext()) {
  298. final Cell next = cellIterator.next();
  299. final CellStyle cellStyle = next.getCellStyle();
  300. final XSSFCell cell = s1Row.createCell(next.getColumnIndex());
  301. final CellType cellType = next.getCellType();
  302. cell.setCellStyle(cellStyle);
  303. switch (cellType) {
  304. case STRING:
  305. cell.setCellValue(next.getStringCellValue());
  306. break;
  307. case FORMULA:
  308. cell.setCellFormula(next.getCellFormula());
  309. continue;
  310. case NUMERIC:
  311. cell.setCellValue(next.getNumericCellValue());
  312. break;
  313. case BOOLEAN:
  314. cell.setCellValue(next.getBooleanCellValue());
  315. }
  316. cell.setCellType(cellType);
  317. }
  318. }
  319. for (CellRangeAddress mergedRegion : mergedRegions) {
  320. target.addMergedRegion(mergedRegion);
  321. }
  322. //移除sourceSheet
  323. workbook.removeSheetAt(sourceSheet);
  324. }
  325. public static void buildExcel(List<Map<String, Object>> list, HSSFWorkbook wb, String sheetName, String[] titleArray, String[] fieldArray, String dest) {
  326. HSSFSheet sheet = wb.createSheet(sheetName);
  327. //样式
  328. //设置默认行高、列宽
  329. sheet.setDefaultRowHeight((short) 500);
  330. sheet.setDefaultColumnWidth(30);
  331. //字体
  332. HSSFFont font = getFont(wb);
  333. //标题字体
  334. HSSFFont titleFont = getWhiteFont(wb);
  335. titleFont.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
  336. //标题样式
  337. CellStyle titleStyle = getCellStyle(wb, titleFont, IndexedColors.GREY_25_PERCENT.getIndex());
  338. //基础样式
  339. CellStyle style = getCellStyle(wb, font);
  340. style.setAlignment(HorizontalAlignment.LEFT);
  341. int firstRowNum = 0;
  342. if (StringUtils.isNotBlank(dest)) {
  343. HSSFFont destFont = getRedFont(wb);
  344. CellStyle destStyle = getCellStyle(wb, destFont);
  345. destStyle.setAlignment(HorizontalAlignment.LEFT);
  346. Row rowDest = sheet.createRow(firstRowNum);
  347. Cell bigDetailTitleCell = rowDest.createCell(0);
  348. bigDetailTitleCell.setCellStyle(destStyle);
  349. bigDetailTitleCell.setCellValue(dest);
  350. sheet.addMergedRegion(new CellRangeAddress(firstRowNum, firstRowNum, 0, fieldArray.length - 1));
  351. firstRowNum++;
  352. }
  353. //第一行,标题
  354. Row row0 = sheet.createRow(firstRowNum);
  355. for (int i = 0; i < titleArray.length; i++) {
  356. Cell cell = row0.createCell(i);
  357. cell.setCellStyle(titleStyle);
  358. cell.setCellValue(titleArray[i]);
  359. }
  360. //第2行开始填充数据
  361. for (int i = 0; i < list.size(); i++) {
  362. //从第2行开始
  363. Row row = sheet.createRow(i + 1 + firstRowNum);
  364. for (int j = 0; j < fieldArray.length; j++) {
  365. Cell cell = row.createCell(j);
  366. cell.setCellStyle(style);
  367. cell.setCellValue(MapUtil.getStr(list.get(i), fieldArray[j], StringUtils.EMPTY));
  368. }
  369. }
  370. }
  371. }

 三、实际业务方法

  1. /**allInfo 所有信息 包括学生、老师、职工的数据List;phoneList 就是需要@的手机号**/
  2. public void receiptDuePaymentReminderPushMsg(AllInfo allInfo, List<String> phoneList) {
  3. //创建一个HSSFWorkbook
  4. HSSFWorkbook wb = new HSSFWorkbook();
  5. // 是否有数据需要构建excel推送
  6. boolean flag0 = studentFileBuild(wb, allInfo.getStudentList(), "", "学生信息");
  7. boolean flag1 = teacherFileBuild(wb, allInfo.getTeacherList(), "", "老师信息");
  8. //TODO 职工可自行补充
  9. boolean flag2 = zhigongFileBuild(wb, allInfo.getZhigongList(), "", "职工信息");
  10. //只要有一个通过就要发送
  11. if (!flag0 && !flag1 && !flag2) {
  12. log.debug("没有需要提醒的数据");
  13. return;
  14. }
  15. //文件名
  16. String fileName = LocalDate.now() + "学校信息汇总.xlsx";
  17. File file = new File(fileName);
  18. try {
  19. // 上传文件
  20. wb.write(file);
  21. // 推送消息:
  22. String text = "【学校通知】\n请查收学校信息汇总表。";
  23. //发送文本消息+excel文件到群
  24. WxPushUtil.sendFileMsg(file, text, phoneList);
  25. } catch (Exception e) {
  26. log.error("发送异常", e);
  27. } finally {
  28. if (file.exists()) {
  29. boolean deleteFlag = file.delete();
  30. log.debug("wxPushMsg delete tmp file: {}", fileName);
  31. }
  32. }
  33. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/178469?site
推荐阅读
相关标签
  

闽ICP备14008679号