根據xlsx模板生成excel數據文件發送郵件代碼
阿新 • • 發佈:2017-06-05
order comment hssf emp value ade 新的 see util
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 "service@****.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數據文件發送郵件代碼