@Autowired
private JavaMailSender mailSender;
#根据数据创建excel
InputStream inputStream = builtExcel(voList);
private InputStream builtExcel(List<MonthlyKeywordEmailVO> voList) {
//创建工作簿
XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
//创建工作表
XSSFSheet xssfSheet = xssfWorkbook.createSheet();
String[] headers = {"关键词", "关键词类型", "计划投放周期"};
XSSFRow xssfRow = xssfSheet.createRow(0);
XSSFCell xssfCell = null;
for (int i = 0; i < headers.length; i++) {
xssfCell = xssfRow.createCell(i);
xssfCell.setCellValue(headers[i]);
}
int rowNum = 1;
XSSFCreationHelper createHelper = xssfWorkbook.getCreationHelper();
for (MonthlyKeywordEmailVO vo : voList) {
xssfRow = xssfSheet.createRow(rowNum++);
xssfCell = xssfRow.createCell(0);
xssfCell.setCellValue(vo.getKeyword());
xssfCell = xssfRow.createCell(1);
xssfCell.setCellValue(vo.getTypeStr());
xssfCell = xssfRow.createCell(2);
xssfCell.setCellValue(vo.getYearAndMonthStr());
}
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
try {
xssfWorkbook.write(bos);
InputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
return inputStream;
} catch (Exception e) {
log.info("monthlyKeywordEmailTask builtExcel Exception:{}", e);
return null;
}
}
#发邮件
sendMail(from, StringUtils.split(to,","), StringUtils.split(cc,","), subject, content, fileName,inputStream);
private void sendMail(String from, String[] to, String[] cc, String subject, String content, String fileName, InputStream inputStream) throws Exception {
MimeMessage message;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(from);
helper.setTo(to);
helper.setCc(cc);
helper.setSubject(subject);
helper.setText(content, true);
helper.addAttachment(MimeUtility.encodeWord(fileName), new ByteArrayResource(IOUtils.toByteArray(inputStream)));
mailSender.send(message);
} catch (Exception e) {
log.info("monthlyKeywordEmailTask 邮箱发送异常:{}", e);
}
}
|