替换excel模板中的内容并使用JavaMail发送邮件
由于在公司工作,常年出差,每天都要以日报的形式向公司汇报当天的工作内容。而日报的内容大体上就只有当天工作的主要内容时变化的,其余的都是不变 的。 而我的电脑刚打开excel有点卡,因此决定使用JavaMail结合poi写一个简单excel模板替换并使用JavaMail发送邮件的小程序。
主要思路如下:
1.加载配置文件(使用yaml作为配置文件)
配置文件中存放的是发送邮件需要用的一些配置信息和excel模板中需要替换的数据
比喻:邮件使用的协议、发送人、收件人、等等信息
2.加载excel模板,读取模板,使用上一步中配置信息替换掉模板中的数据,然后生成excel文件
3.使用JavaMail发送邮件
要注意乱码的处理。
4.将代码打包成一个可执行的Jar包(最终只需要修改一下配置文件即可使用)
5.项目的源代码,用附件上传失败了。 链接:http://pan.baidu.com/s/1dDCU593 密码:6xpi
项目采用maven构建,但是为了修改配置文件方便,并没有使用maven的规范,将配置文件放到src/main/resources目录中。
代码如下:
/**
* 读取yaml配置文件,读取excel模板并生成excel文件,在使用JavaMail发送。
*
* @author huan
*
*/
public class App {
// 配置文件的名称
private static final String CONFIGER_YAML_FILE_NAME = "sendMailConfig.yaml";
// 日报的excel模板
private static final String EXCEL_TEMPLETE = "ExcelTemplete.xls";
public static void main(String[] args) {
// 1.加载属性文件
Map<String, String> propMap = null;
try {
propMap = loadConfigYamlFile();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
System.out.println("加载yaml文件失败");
System.exit(1);
}
// 将当前日期放到map中
propMap.put("${currDate}", new SimpleDateFormat("yyyyMMdd").format(new Date()));
System.out.println("输出配置文件信息开始...");
for (Map.Entry<String, String> entry : propMap.entrySet()) {
System.out.println(entry.getKey() + " --> " + entry.getValue());
}
System.out.println("输出配置文件信息结束...");
// 2.加载excel模板
Workbook workbook = loadExcelTemplete();
if (workbook == null) {
return;
}
// 3.获取第一个sheet页
Sheet sheet = workbook.getSheetAt(0);
if (null == sheet) {
System.out.println("获取第一个sheet页失败");
return;
}
String dayReportName = "Test-日报-" + propMap.get("${reportPer}") + "-" + propMap.get("${currDate}") + ".xls";
System.out.println("生成新的日报的名称:" + dayReportName);
// 替换模板中的内容
for (Row row : sheet) {
for (Cell cell : row) {
int cellType = cell.getCellType();
// 根据单元格的中内容的类型,得到单元格中的值
String cellContent = getCellContentByCellType(cell, cellType);
if (propMap.containsKey(cellContent)) {
setCellValue(propMap, cell, cellContent);
}
}
}
// 将替换后的数据excel保存到本地
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(dayReportName));
workbook.write(bos);
workbook.close();
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println(dayReportName + " --> 生成成功!!!");
// 发送邮件开始
try {
sendMail(propMap, dayReportName);
} catch (Exception e) {
e.printStackTrace();
System.out.println("邮件发送失败");
System.exit(1);
}
System.out.println("邮件发送成功");
// 归档文件
archiveFile(dayReportName);
}
// 归档日报
private static void archiveFile(String dayReportName) {
// 1.判断目录是否存在
Calendar calendar = Calendar.getInstance();
int _month = calendar.get(Calendar.MONTH) + 1;
String month = _month + "";
if (_month < 10) {
month = "0" + _month;
}
String dir = "日报归档" + File.separator + month;
File dirFile = new File(dir);
if (!dirFile.exists()) {
dirFile.mkdirs();
System.out.println("创建目录:" + dirFile.getAbsolutePath());
}
File dayReportFile = new File(dayReportName);
File f = new File(dir, dayReportName);
dayReportFile.renameTo(f);
System.out.println("文件归档成功:" + f.getAbsolutePath());
}
/**
* 发送日报
*
* @param propMap
* @param dayReportName
* @throws MessagingException
* @throws IOException
*/
private static void sendMail(final Map<String, String> propMap, String dayReportName) throws MessagingException, IOException {
Properties props = new Properties();
props.setProperty("mail.host", propMap.get("${mail.host}"));
props.setProperty("mail.smtp.auth", propMap.get("${mail.smtp.auth}"));
props.setProperty("mail.transport.protocol", propMap.get("${mail.transport.protocol}"));
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 邮箱的用户名和密码
return new PasswordAuthentication(propMap.get("${sendPer}"), propMap.get("${sendPerPwd}"));
}
};
// 1.创建邮件的第一步: 创建session对象
Session session = Session.getInstance(props, auth);
// 设置调试模式 可以关闭
session.setDebug(true);
// 2.创建邮件的第二步:创建MimeMessage对象
// 创建邮件对象
MimeMessage msg = new MimeMessage(session);
// 设置发送人
msg.setFrom(new InternetAddress(propMap.get("${sendPer}")));
// 设置收件人
msg.addRecipients(RecipientType.TO, InternetAddress.parse(propMap.get("${receivePer}")));
// 设置收件人 类型为 抄送
msg.addRecipients(RecipientType.CC, InternetAddress.parse(propMap.get("${CC}")));
// 设置邮件的主题
msg.setSubject(dayReportName);
MimeMultipart partList = new MimeMultipart();
// 写签名
MimeBodyPart part1 = new MimeBodyPart();
System.out.println(propMap.get("${mailSign}"));
part1.setContent(propMap.get("${mailSign}"), "text/html;charset=utf-8");
// 写附件
MimeBodyPart part2 = new MimeBodyPart();
part2.attachFile(new File(dayReportName));
part2.setFileName(MimeUtility.encodeText(dayReportName));
// 把部件添加到集合中
partList.addBodyPart(part1);
partList.addBodyPart(part2);
msg.setContent(partList);
// 3. 创建邮件的第三步,发送 Transport
Transport.send(msg);
}
/**
* 设置单元格的样式
*
* @param propMap
* @param cell
* @param cellContent
*/
private static void setCellValue(Map<String, String> propMap, Cell cell, String cellContent) {
if (cellContent.equals("${currDate}")) {// 日期单独处理
System.out.println("替换[" + cellContent + "]为[" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "]");
cell.setCellValue(new Date());
} else {
String cellValue = propMap.get(cellContent);
System.out.println("替换[" + cellContent + "]为[" + cellValue + "]");
cell.setCellValue(cellValue);
}
}
/**
* @param cell
* @param cellType
*/
private static String getCellContentByCellType(Cell cell, int cellType) {
String cellContent = "";
switch (cellType) {
case Cell.CELL_TYPE_STRING:
cellContent = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BLANK:
cellContent = "";
break;
case Cell.CELL_TYPE_NUMERIC:
cellContent = cell.getNumericCellValue() + "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellContent = cell.getBooleanCellValue() + "";
break;
default:
System.err.println("出现未知的单元格类型,系统退出。");
System.exit(1);
break;
}
return cellContent;
}
/**
* 生成Excel的模板
*
* @throws IOException
* @throws FileNotFoundException
*/
private static Workbook loadExcelTemplete() {
try {
Workbook workbook = WorkbookFactory.create(new FileInputStream(new File(EXCEL_TEMPLETE)));
return workbook;
} catch (Exception e) {
System.out.println("加载Excel模板出错...");
e.printStackTrace();
}
return null;
}
// 加载配置文件文件
@SuppressWarnings("unchecked")
private static Map<String, String> loadConfigYamlFile() throws FileNotFoundException {
Yaml yaml = new Yaml();
Iterable<Object> iterable = yaml.loadAll(new FileInputStream(new File(CONFIGER_YAML_FILE_NAME)));
Iterator<Object> it = iterable.iterator();
Map<String, String> configerMap = new HashMap<String, String>();
while (it.hasNext()) {
Map<String, String> map = (Map<String, String>) it.next();
for (Map.Entry<String, String> entry : map.entrySet()) {
configerMap.put("${" + entry.getKey().trim() + "}", entry.getValue().trim());
}
}
return configerMap;
}
}
| 项目截图如下: | 最终打包成的目录如下: |
| 点击run.bat执行后,就可以看到 | |
替换excel模板中的内容并使用JavaMail发送邮件的更多相关文章
- JAVA POI替换EXCEL模板中自定义标签(XLSX版本)满足替换多个SHEET中自定义标签
个人说明:为了简单实现导出数据较少的EXCEL(根据自定义书签模板) 一.替换Excel表格标签方法```/** * 替换Excel模板文件内容 * @param map * 需要替换的标签建筑队形式 ...
- java代码将excel文件中的内容列表转换成JS文件输出
思路分析 我们想要把excel文件中的内容转为其他形式的文件输出,肯定需要分两步走: 1.把excel文件中的内容读出来: 2.将内容写到新的文件中. 举例 一张excel表中有一个表格: 我们需要将 ...
- 根据excel表格中的内容更新Sql数据库
关于[无法创建链接服务器 "(null)" 的 OLE DB 访问接口 SQL Server 2008读取EXCEL数据时,可能会报这个错误:无法创建链接服务器 "(nu ...
- C# 导出数据到Excel模板中(转)
今天做报表的时候遇到了多表头的问题,而且相应的报表的格式都一样.所以就采用了报表模板的方式来进行. 第一步:在开发的当前项目中引入:Microsoft.Office.Interop.Excel:Sys ...
- 从Excel文件中读取内容
从Excel文件中读取内容 global::System.Web.HttpPostedFileBase file = Request.Files["txtFile"]; strin ...
- 根据Excel文件中的内容,修改指定文件夹下的文件名称
问题:根据Excel文件中内容,把文件名称由第2列,改为第1列.比如:把文件“123.jpg”修改为“1.jpg”.
- 用配置文件里面的参数值替换yaml模板中的变量值【python】
用配置文件里面的参数值替换yaml模板中的变量值[python] #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/20 1 ...
- poi读取excel模板,填充内容并导出,支持导出2007支持公式自动计算
/** * 版权所有(C) 2016 * @author www.xiongge.club * @date 2016-12-7 上午10:03:29 */ package xlsx; /** * @C ...
- POI根据EXCEL模板,修改内容导出新EXCEL (只支持HSSF)
package excelPoiTest; import java.io.File; import java.io.FileInputStream; import java.io.FileOutput ...
随机推荐
- python-request 实现企业微信接口自动化-1(DDT)
环境准备 python+requests 读取企业微信api开发文档,得知调用企业微信接口必须先获取企业微信的accesstoken是通过 ("corpid","&quo ...
- Redis——set,hash与列表
一.List列表 基于Linked List实现 元素是字符串类型 列表头尾增删快,中间增删慢,增删元素是常态 元素可以重复出现 最多包含2^32-1元素 列表的索引 从左至右,从0开始 从右至左,从 ...
- 在windows中给git修改默认的编辑器为sublime
首先,需要配置sublime的为环境变量,这是为了让git能通过命令调用sublime.也可以写一个.bat脚本.然后,让git调用bat脚本也可以 配置环境变量path到subl.exe的目录 脚本 ...
- go build 与go install
相同点都能生成可执行文件 不同点go build 不能生成包文件, go install 可以生成包文件go build 生成可执行文件在当前目录下, go install 生成可执行文件在bin目录 ...
- 记录centos下nl与cat -n的不同
nl命令列出文件行不包含空格,cat -n包含空格 [root@bogon ~]# cat -n test.txt 1 a 2 aa 3 aaa 4 aaaa 5 aaaaa 6 7 aaaaaa [ ...
- crontab 语法和最快速的学习
1.Cron 时间表语法 # ┌───────────── 分钟 (0 - 59) # │ ┌───────────── 小时 (0 - 23) # │ │ ┌───────────── 月的某天 ( ...
- Docker 网络类型
Docker 网络类型 前言 a. 本文主要为 Docker的视频教程 笔记. b. 环境为 CentOS 7.0 云服务器 c. 上一篇:docker-compose 的使用和负载均衡的初探 1. ...
- scrum项目冲刺_day07总结
摘要:今日完成任务. 1.短信服务正在进行 2.路线规划正在进行 总任务: 一.appUI页面(已完成) 二.首页功能: 1.图像识别功能(已完成) 2.语音识别功能(已完成) 3.垃圾搜索功能 4. ...
- 有备无患「GitHub 热点速览 v.21.38」
作者:HelloGitHub-小鱼干 数据库最重要的一个功能是容灾备份,备份不只是对数据库重要,对日常工作生活的我们一样重要,比如花了一个工作日写的代码没有备份(虽然可能只有 1 行-)总归是一个让人 ...
- 重新整理 .net core 周边阅读篇————AspNetCoreRateLimit[一]
前言 整理了一下.net core 一些常见的库的源码阅读,共32个库,记100余篇. 以下只是个人的源码阅读,如有错误或者思路不正确,望请指点. 正文 github 地址为: https://git ...