1. 程式人生 > >根據xlsx模板生成excel資料檔案傳送郵件程式碼

根據xlsx模板生成excel資料檔案傳送郵件程式碼

package mail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List; import java.util.Map; import javax.mail.internet.MimeUtility; import org.apache.commons.mail.EmailAttachment; import org.apache.commons.mail.MultiPartEmail; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * @comments * @author xxx * @version 建立時間:2014年6月15日 * 將該類從單例項,變成了 Spring 管理的類 */ public class EmailService { private final static String EMAIL_APP_TYPE = "email";
// private static final String INSURANCE_EMAIL_TYPE="insurance_email"; private final static String HOST_NAME_ITEM_NAME = "server_host"; private final static String FROM_ADDR_ITEM_NAME = "from_addr"; private final static String FROM_NAME_ITEM_NAME = "from_name"; private final static String PASSWORD_ITEM_NAME = "password"; // private final static String TO_EMAIL_ITEM_NAME = "to_email"; //傳送物件。 private static final String CPIC_TEMPLET_FILE = "C:\\hzCoupon2.xlsx"; //模板檔案 public static String getHostName() { return "smtp.***.***.com"; } public static String getPassword() { return "pwd**"; } public static String getFromAddr() { return "[email protected]****.com"; } public static String getFromName() { return "****Service"; } /** * 入口 * @param list * @throws Exception */ public static boolean sendPolicyEmail(String toEmail,List<HzCouponModel> list) throws Exception{ boolean result = false; // String currTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());//System.currentTimeMillis(); Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_MONTH, -1); //往前一天 String yesterday = "-test-"; //xxxx年xx月xx日 String cpicFileName = "hzCoupon" + yesterday + ".xls"; try { String fileNames = createHzCouponXLS(list, cpicFileName); if(fileNames != null && !"".equals(fileNames)){ sendEmailWithAttch(toEmail,fileNames); result = true; } } catch (Exception e) { result = false; e.printStackTrace(); throw e; } return result; } private static void sendEmailWithAttch(String toEmail, String cpicNamePath) throws Exception{ String yesterday = "-test-"; EmailAttachment insurAttach = getAttachment("***保資料"+yesterday+".xlsx", cpicNamePath, "***保資料(**提供)"); Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_MONTH, -1); //往前一天 // String yesterday = CommonConstants.DATE_YEAR_MONTH_DAY_CN_FORMAT(c.getTime()); //xxxx年xx月xx日 String res1 = sendAttchEmail(toEmail, "***保資料"+yesterday+"明細", "你好,附件是"+yesterday+"***保資料表格,請查收。", insurAttach); System.out.println("傳送“***資格資料” email res:{}"+ res1); } private static EmailAttachment getAttachment(String attachName, String fileNamePath, String desc) throws Exception{ EmailAttachment attachment = new EmailAttachment(); attachment.setPath(fileNamePath); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setName(MimeUtility.encodeText(attachName)); attachment.setDescription(desc); return attachment; } private static String sendAttchEmail(String to, String subject, String content, EmailAttachment attachment) throws Exception{ MultiPartEmail email = new MultiPartEmail(); email.setHostName(getHostName()); email.setAuthentication(getFromAddr(), getPassword()); email.setFrom(getFromAddr(), getFromName()); email.addTo(to); email.setSubject(subject); email.setMsg(content); email.attach(attachment); email.addHeader("Disposition-Notification-To", getFromAddr());//郵件回執 return email.send(); } /** * 獲取模板檔案流 * @return */ private static InputStream getCpicTemplet(){ // return CpicCouponEmailService.class.getResourceAsStream(CPIC_TEMPLET_FILE); //檔案流 InputStream in = null; File f = new File(CPIC_TEMPLET_FILE); try { in = new FileInputStream(f); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return in; } @SuppressWarnings("unchecked") private static String createHzCouponXLS(Object data, String cpicFileName) throws Exception{ InputStream assIn = null; FileOutputStream assOut = null; try { //------------------------------------------------------------------------------------------------------------ assIn = getCpicTemplet();//InsuranceUtils.class.getResourceAsStream("/conf/resource/Roadside-Assistance.xlsx"); XSSFWorkbook assWb = new XSSFWorkbook(assIn);//XSSFWorkbook assWb = (XSSFWorkbook) WorkbookFactory.create(assIn); XSSFSheet assSheet = assWb.getSheetAt(0); // String currDate = new SimpleDateFormat("yyyy/MM/dd").format(new Date()); if(data instanceof List){ List<HzCouponModel> list = (List<HzCouponModel>) data; for (int i = 0; i < list.size() ; i++) { HzCouponModel model = list.get(i); setData(i, model, assWb, assSheet); } }else if(data instanceof Map){ HzCouponModel model = (HzCouponModel) data; setData(0, model, assWb, assSheet); }else{ return null; } // String insurPolicyNamePath = File.createTempFile(cpicFileName,".xlsx").getPath(); //臨時檔案 String insurPolicyNamePath = "C:/save/"+cpicFileName; assOut = new FileOutputStream(insurPolicyNamePath); assWb.write(assOut);//寫入Excel檔案,這才是關鍵。 System.out.println("建立“***保資料”Excel檔案:{}" + insurPolicyNamePath); return insurPolicyNamePath; } catch (Exception e) { e.printStackTrace(); throw e; }finally{ if(assOut != null){ assOut.close(); } if(assIn != null){ assIn.close(); } } } /** * 資料填充 * @param idx * @param currDate * @param map * @param insruWb * @param insurSheet * @param assWb * @param assSheet * @throws Exception */ private static void setData(int idx, HzCouponModel model, XSSFWorkbook assWb, XSSFSheet assSheet) throws Exception{ XSSFRow assRow = createRowAndCel(assWb, assSheet, idx+1, 12);//assSheet.getRow(i+1);//可能為null assRow.getCell(0).setCellValue(model.getCreateTime());// assRow.getCell(1).setCellValue(model.getPartner());// assRow.getCell(2).setCellValue(model.getStartPolicyDate());// assRow.getCell(3).setCellValue(model.getFiliale());// assRow.getCell(4).setCellValue(model.getBranch());// assRow.getCell(5).setCellValue(model.getPolicyMobile());// assRow.getCell(6).setCellValue(model.getInsuredMobile());// assRow.getCell(7).setCellValue(model.getBrandType());// assRow.getCell(8).setCellValue(model.getPlateNum());// assRow.getCell(9).setCellValue(model.getFrameNo());// assRow.getCell(10).setCellValue(model.getCouponType());// assRow.getCell(11).setCellValue(model.getInsuredNumber());// } /** * 建立Excel的行(row)和列(cel) * @param sheet * @param rowIdx * @param cellNum */ private static XSSFRow createRowAndCel(XSSFWorkbook wb, XSSFSheet sheet, int rowIdx, int cellNum){ XSSFCellStyle cellStyle = wb.createCellStyle();//建立cell樣式 cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//設定右邊框 cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);//設定下邊框 sheet.createRow(rowIdx); XSSFRow row = sheet.getRow(rowIdx); for (int i = 0; i < cellNum; i++) { XSSFCell cell = row.createCell(i); cell.setCellStyle(cellStyle); } return row; } //錯誤: 找不到或無法載入主類 testJava2.email.CpicCouponEmailService public static void main(String[] args) throws Exception{ List<HzCouponModel> list = new ArrayList<HzCouponModel>(); HzCouponModel model = new HzCouponModel("2017-06-04", "*保", "2017-06-06", "sz分公司", "電子商務部門", "137****1198", "137****1199", "奧迪A8", "滬A***78", "WFSFJFKSJFa7844", "經濟型套餐", "3100245456"); list.add(model); model = new HzCouponModel("2017-06-04", "*安", "2017-06-08", "sz分公司", "電子商務部門", "137****2298", "137****2299", "奧迪A8", "滬A**78", "WFSFJFKSJFa7844", "豪華型套餐", "3100245456"); list.add(model); sendPolicyEmail("[email protected]", list); } }

1.異常處理

Exception in thread "main" org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException: The supplied data appears to be in the OLE2 Format. You are calling the part of POI that deals with OOXML (Office Open XML) Documents. You need to call a different part of POI to process this data (eg HSSF instead of XSSF)

 原因是:
HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,副檔名是.xls 
XSSFWorkbook:是操作Excel2007的版本,副檔名是.xlsx

2.NoClassDefFoundError: org/openxmlformats/schemas/drawingml/x2006/main/ThemeDocument

解決方法:新增poi-ooxml-schemas-3.12-20150511.jar

3. javax.mail.NoSuchProviderException: smtp 報錯

下了最新的mailapi  1.4.7  版本,  把原來的那兩個jar(activation-1.1.1.jar  和 mailapi-1.4.3 jar)從classpath中去掉, 把1.4.7 中lib全部加到classpath, 然後就傳送成功了。 

相關推薦

根據xlsx模板生成excel資料檔案傳送郵件程式碼

package mail; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.

根據xlsx模板生成excel數據文件發送郵件代碼

order comment hssf emp value ade 新的 see util package mail; import java.io.File; import java.io.FileInputStream; import java.io.FileNotF

使用T4模板根據資料庫自動生成類類檔案

一個數據庫可能有多個表,需要生成多個類檔案,首先建立一個xx.ttinclude檔案.此檔案主要能夠生成單獨的類檔案。同時再定義一個類DBHelper來獲取資料庫裡所有表的資訊和資料。 <#@ assembly name="System.Core"#><#@ assembly nam

java使用itext操作填充pdf模板,(根據一個模板生成多頁資料

直接開始需要兩個jar包 itext-asian-5.2.0.jar和 itextpdf-5.5.6.jar ,我的業務邏輯可能比較複雜,在這裡我就簡單的提供一個demo ,需要的人自己按照自己的業務邏輯來改。 首先我們要用 Adobe Acrobat 來編輯p

c#讀取生成excel表格檔案xls、xlsx格式檔案

全棧工程師開發手冊 (作者:欒鵬) c#儲存生成excel表格格式xls、xlsx格式的檔案 需要電腦安裝對應版本的office,並且在專案中引用excel 測試程式碼 static void Main() { List<

Java根據模板生成excel並下載

需要用到的jar包有freemarker-2.3.18.jar,freemarker-util-0.0.1-SNAPSHOT.jar,jxl-2.6.10.jar,jxl-report-1.0.jar,這些網上都有,可以去找 來吧,直接上乾貨。excel模板如圖: 很容

使用 poi 根據 word 模板生成 word 檔案

本例子是一個 maven 專案,要引入 poi 的依賴片段如下: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi&

後端根據查詢條件生成excel文件返回給前端,vue進行下載

win urn his rim ech spa href col abi 一、HTML代碼 <el-col :xs="2" :md="2" :sm="3"> <el-button type="primary" style="width:100%;

在Angular裡用,純js plugin js-xlsx外掛生成excel報表

在Angular裡用,用純js plugin外掛生成excel報表,用到如下外掛, // Browser save file (compatibility) (click to show) https://github.com/SheetJS/js-xlsx https://github

Java生成excel報表檔案

此次簡單的操作將資料從資料庫匯出生成excel報表以及將excel資料匯入資料庫 首先建立資料庫的連線池: package jdbc; import java.io.FileInputStream; import java.sql.Connection; i

Java根據Word模板生成Word文件(Freemarker實現)

public class WordExportUtil { private static Configuration configuration; static { configuration = new Configuration(); configur

PHP生成excel表格檔案並下載

利用php匯出excel我們大多會直接生成.xls檔案,這種方便快捷。 function createtable($list,$filename){ header("Content-ty

使用poi通過excel模板匯出excel資料

期望:用預先的xlsx的Excel表格模板參考:兩篇部落格步驟:模板+資料:相關jar報 座標:(注意jar版本 否則再tempWorkBook = new XSSFWorkbook(inputstre

php根據word模板生成新的word文件

sso roc 信息 使用 docs offic value 文件 安裝 原文地址:http://www.niu12.com/article/16 php使用phpword將word內容變量替換 a.安裝phpword composer require phpoffice

powerdesiger 生成excel 資料字典

先使用逆向工程生產物理模型,然後ctrl + shift +x 開啟視窗執行一下指令碼'****************************************************************************** Option Explici

java根據ftl模板生成word文件(列表)

1、在專案開發中很多時候我們要做的事匯出資料列表,那麼如果使用freemarker的時候,list也是不會少的 <#list datelist ?sort_by("name") as data>//根據name排序 reverse為降序 <#list

根據xml文件編寫dtd檔案並用java程式碼測試

xml檔案:<應聘資訊> <應聘者> <姓名> 張三 </姓名> <碩士> 湖南大學計算機理學碩士 </碩士> <獎勵> 獲得計算機競賽

eclipse建立maven工程讀取hdfs檔案傳送郵件

1、在maven下新建maven工程 2、編寫程式碼 package WorkFlow.Mail; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamR

kettle從mysql中查詢出特定的資料然後傳送郵件附件到指定的郵箱。

剛開始接觸kettle,還是小白,但是感覺這東西挺強大。 做了一個傳送附件excel到指定郵箱的demo。現在記錄如下。 1. 2. 3. . 4.job檔案 新建job檔案,在空白處設定屬性 5.拖入以下按鈕 設定郵件引數 到這裡應該就差不多了,執行成功的截

Python | 定時壓縮指定資料傳送郵件

工作中每天需要收集部門內的FR檔案,傳送給外部部門的同事幫忙上傳,這麼發了有大半年,昨天亮光一閃,為什麼不做成自動化呢,於是用python實現了整個流程,今天體驗了一下真是美滋滋。 程式碼如下 首先匯入需要的包 import win32com.