一.EasyPOI依赖
<!-- easypoi的支持 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.4.0</version>
</dependency>
<!--发送邮件依赖-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.1</version>
</dependency>
二.Excel模板 三.代码部分
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.cookie.entity.*;
import com.cookie.utils.EmailUtils;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
public class demo {
public static void main(String[] args) throws IOException {
List<ExportData> list = new ArrayList<>();
ExportData req = new ExportData();
req.setOutAccount("123455");
req.setOutAccountName("xxxx银行");
req.setReceiptAccountWhereitis("xxx");
req.setCurrency("人民币");
req.setTradingHours("2022-12-22");
req.setValueDate("2022-12-22");
req.setTradeType("test");
req.setAmount(new BigDecimal(1));
req.setLoan("1");
req.setBalance(new BigDecimal(2));
req.setDealFlow("11112223333");
req.setReceiptAccountName("Kata");
req.setReceiptAccount("66666");
req.setRecentDealFlow("000000");
list.add(req);
TemplateExportParams params = new TemplateExportParams("template/模板.xls");
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
long total = list.stream().filter(exportData -> "1".equals(exportData.getLoan())).count();
BigDecimal lendTotal = list.stream().filter(exportData -> "1".equals(exportData.getLoan())).map(ExportData::getAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
BigDecimal loanTotal = list.stream().filter(exportData -> "2".equals(exportData.getLoan())).map(ExportData::getAmount).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
Map<String, Object> map = new HashMap<String, Object>();
map.put("outAccount", list.get(0).getOutAccount());
map.put("outAccountName", list.get(0).getOutAccountName());
map.put("createDate", simpleFormat.format(new Date()));
map.put("loanAmount", loanTotal);
map.put("totalLend", total);
map.put("balance", list.get(list.size() - 1).getBalance());
map.put("lendAmount", lendTotal);
map.put("startTime", list.get(0).getValueDate());
map.put("endTime", list.get(0).getValueDate());
List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
for (ExportData exportData : list) {
Map<String, String> lm = new HashMap<String, String>();
lm.put("outAccount", exportData.getOutAccount());
lm.put("outAccountName", exportData.getOutAccountName());
lm.put("currency", "人民币");
lm.put("tradingHours", exportData.getTradingHours());
lm.put("valueDate", exportData.getValueDate());
lm.put("tradeType", exportData.getTradeType());
lm.put("amount", String.valueOf(exportData.getAmount()));
lm.put("loan", "1".equals(exportData.getLoan()) ? "借" : "贷");
lm.put("balance", String.valueOf(exportData.getBalance()));
lm.put("dealFlow", exportData.getDealFlow());
lm.put("receiptAccountName", exportData.getReceiptAccountName());
lm.put("receiptAccount", exportData.getReceiptAccount());
lm.put("receiptAccountWhereitis", exportData.getReceiptAccountWhereitis());
listMap.add(lm);
}
map.put("maplist", listMap);
Workbook workbook = ExcelExportUtil.exportExcel(params, map);
ByteArrayOutputStream fos = new ByteArrayOutputStream();
workbook.write(fos);
ByteArrayInputStream inputStream = new ByteArrayInputStream(fos.toByteArray());
EmailUtils.sendEmail("收件人邮箱","邮件主题","邮件内容",inputStream);
fos.close();
}
}
发邮件工具类1,以腾讯企业邮箱为例(需要邮箱密码)
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
@Component
@Slf4j
public class EmailUtils {
private static final String PROTOCOL = "smtp";
private static final String HOST = "smtp.exmail.qq.com";
private static final String PORT = "465";
private static final String ACCOUNT = "发送人邮箱";
private static final String PASS = "发送人邮箱密码";
private static final String PERSONAL = "发件人别名";
static class MyAuthenricator extends Authenticator {
String u = null;
String p = null;
public MyAuthenricator(String u, String p) {
this.u = u;
this.p = p;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(u, p);
}
}
public static boolean sendEmail(String recipients, String subject, String content, InputStream is) {
Properties prop = new Properties();
prop.setProperty("mail.transport.protocol", PROTOCOL);
prop.setProperty("mail.smtp.host", HOST);
prop.setProperty("mail.smtp.port", PORT);
prop.setProperty("mail.smtp.auth", "true");
MailSSLSocketFactory mailSSLSocketFactory = null;
try {
mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
Session session = Session.getDefaultInstance(prop, new MyAuthenricator(ACCOUNT, PASS));
MimeMessage mimeMessage = new MimeMessage(session);
try {
if (StringUtils.isNotBlank(PERSONAL)){
mimeMessage.setFrom(new InternetAddress(ACCOUNT, PERSONAL));
}
else {
mimeMessage.setFrom(new InternetAddress(ACCOUNT));
}
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
mimeMessage.setSubject(subject);
mimeMessage.setSentDate(new Date());
Multipart mp = new MimeMultipart();
MimeBodyPart body = new MimeBodyPart();
body.setText(content);
mp.addBodyPart(body);
MimeBodyPart bodyPart = new MimeBodyPart();
DataSource dataSource = new ByteArrayDataSource(is,"application/msexcel");
bodyPart.setDataHandler(new DataHandler(dataSource));
bodyPart.setFileName(MimeUtility.encodeText("交易明细.xls"));
mp.addBodyPart(bodyPart);
mimeMessage.setContent(mp);
mimeMessage.saveChanges();
Transport.send(mimeMessage);
log.info("Send email successfully....");
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
发邮件工具类2(需要邮箱授权码)
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.InputStream;
import java.util.Properties;
@Component
@Slf4j
public class SendEmailUtils {
public static void sendFileEmail(String toEmail, InputStream is,String fromEmail,String authCode) {
Transport transport = null;
String host = "smtp.qq.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, authCode);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
message.setSubject("邮件主题");
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
contentPart.setText("邮件的文本内容");
multipart.addBodyPart(contentPart);
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(is, "application/msexcel");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(MimeUtility.encodeText("交易明细.xls"));
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.saveChanges();
Transport.send(message, message.getAllRecipients());
log.info("Send email successfully....");
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果:
|