java 邮件发送表格

问题导入

在一些定时任务中,经常会出现发送邮件的需求。最近,本人就碰上一个发送邮件表格而不是作为附件发送的需求。

效果图

在这里插入图片描述
这种效果,实际上是在邮件正文里面填入HTML语言来实现的 。

实现方案

在网上搜索后,我发现了有三中普遍的实现方式。

1. 拼接HTML文件(不推荐)

这种方案,类似于写html文件一样写出来。只适合非常简单的表格。拼接和填充数据都需要自己手写。
代码大概是这样子。

StringBuilder content = new StringBuilder("<html><head></head><body>");
        content.append("<table border=\"1\" style=\"width:1000px; height:150px;border:solid 1px #E8F2F9;font-size=14px;font-size:18px;\">");
        content.append("<tr style=\"background-color: #428BCA; color:#ffffff\"><td rowspan=\"3\">交易时间</td>" +
                "<td colspan=\"4\">实名认证</td>");
        content.append("<tr>" +
                "<td colspan=\"2\">支付中心</td>" +
                "<td colspan=\"2\">业务线</td>" +
                "</tr>");
        content.append("<tr><td>笔数</td><td>金额</td><td>笔数</td><td>金额</td></tr>");
        content.append("<tr>" +
                "<td><span>20201118</span></td>" +
                "<td><span>0</span></td>" +
                "<td><span>0.00</span></td>" +
                "<td><span>0</span></td>" +
                "<td><span>0.00</span></td>" +
                "</tr>");
        content.append("</table>");
        content.append("<h3>对账无误</h3>");
        content.append("</body></html>");

引用的他人的代码片段。不想手写 o(╥﹏╥)o

效果
在这里插入图片描述

2. excel 转HTML

这种方案巧妙的避开了生成html文件的繁琐。避重就轻,直接操作更容易实现的excel来生成html代码。

使用工具类来转化

依赖
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.18</version>
</dependency>

<dependency>
    <groupId>org.apache.xmlbeans</groupId>
    <artifactId>xmlbeans</artifactId>
    <version>3.1.0</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.21</version>
</dependency>

工具类


import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class Excel2HtmlUtil {
    /**
     *
     * @param filePath    excel源文件文件的路径
     * @param htmlPositon 生成的html文件的路径
     * @param isWithStyle 是否需要表格样式 包含 字体 颜色 边框 对齐方式
     * @throws Exception
     *
     */
    public static String readExcelToHtml(String filePath, String htmlPositon, boolean isWithStyle,String type,String attname) throws Exception {
        InputStream is = null;
        String htmlExcel = null;
        Map<String,String> stylemap = new HashMap<String,String>();
        try {
            if("csv".equalsIgnoreCase(type)) {
                htmlExcel = getCSVInfo(filePath,htmlPositon);
                writeFile1(htmlExcel, htmlPositon,stylemap,attname);
            }else {
                File sourcefile = new File(filePath);
                is = new FileInputStream(sourcefile);
                Workbook wb = WorkbookFactory.create(is);
                if (wb instanceof XSSFWorkbook) { // 03版excel处理方法
                    XSSFWorkbook xWb = (XSSFWorkbook) wb;
                    htmlExcel = getExcelInfo(xWb, isWithStyle,stylemap);
                } else if (wb instanceof HSSFWorkbook) { // 07及10版以后的excel处理方法
                    HSSFWorkbook hWb = (HSSFWorkbook) wb;
                    htmlExcel = getExcelInfo(hWb, isWithStyle,stylemap);
                }
                writeFile(htmlExcel, htmlPositon,stylemap,attname);
            }
        } catch (Exception e) {
            System.out.println("文件被损坏或不能打开,无法预览");
            //throw new Exception("文件被损坏或不能打开,无法预览");
        } finally {
            try {
                if(is!=null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return htmlPositon;
    }

    private static void getcscvvalue(BufferedReader reader,List col,String oldvalue,List list) {
        String line = null;
        try {
            while((line=reader.readLine())!=null){
                String[] item = line.split(",",-1);
                boolean isbreak = false;
                for(int i=0;i<item.length;i++) {
                    String value = item[i];
                    if(value.endsWith("\"")) {
                        value = oldvalue+value;
                        col.add(value);
                    }else if(item.length==1) {
                        value = oldvalue+value;
                        getcscvvalue(reader,col,value,list);
                        isbreak = true;
                    }else if(value.startsWith("\"")){
                        getcscvvalue(reader,col,value,list);
                        isbreak = true;
                    }else {
                        col.add(value);
                    }
                }
                if(!isbreak) {
                    list.add(col);
                    col = new ArrayList();
                }
            }
        } catch (IOException e) {
        }
    }

    private static String getCSVInfo(String filePath,String htmlPositon) {
        StringBuffer sb = new StringBuffer();
        DataInputStream in = null;
        try {
            in=new DataInputStream(new FileInputStream(filePath));
            BufferedReader reader=new BufferedReader(new InputStreamReader(in));
            //reader.readLine();
            String line = null;
            List list = new ArrayList();
            while((line=reader.readLine())!=null){
                String[] item = line.split(",");
                List col = new ArrayList();
                for(int i=0;i<item.length;i++) {
                    String value = item[i];
                    if(value.startsWith("\"")) {
                        getcscvvalue(reader,col,value,list);
                    }else {
                        col.add(value);
                    }
                }
                list.add(col);
            }
            sb.append("<table>");
            for(int i=0;i<list.size();i++) {
                List col = (List) list.get(i);
                if(col==null||col.size()==0) {
                    sb.append("<tr><td ></td></tr>");
                }
                sb.append("<tr>");
                for(int j=0;j<col.size();j++) {
                    String value = (String) col.get(j);
                    if (value == null||"".equals(value)) {
                        sb.append("<td> </td>");
                        continue;
                    }else {
                        sb.append("<td>"+value+"</td>");
                    }
                }
                sb.append("</tr>");
            }
            sb.append("</table>");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    //读取excel文件,返回转换后的html字符串
    private static String getExcelInfo(Workbook wb, boolean isWithStyle, Map<String,String> stylemap) {
        StringBuffer sb = new StringBuffer();
        StringBuffer ulsb = new StringBuffer();
        ulsb.append("<ul>");
        int num = wb.getNumberOfSheets();
        //遍历excel文件里的每一个sheet
        for(int i=0;i<num;i++) {
            Sheet sheet = wb.getSheetAt(i);// 获取第i个Sheet的内容
            String sheetName = sheet.getSheetName();
            if(i==0) {
                ulsb.append("<li id='li_"+i+"' class='cur' οnclick='changetab("+i+")'>"+sheetName+"</li>");
            }else {
                ulsb.append("<li id='li_"+i+"' οnclick='changetab("+i+")'>"+sheetName+"</li>");
            }
            int lastRowNum = sheet.getLastRowNum();
            Map<String, String> map[] = getRowSpanColSpanMap(sheet);
            Map<String, String> map1[] = getRowSpanColSpanMap(sheet);
            sb.append("<table id='table_"+i+"' ");
            if(i==0) {
                sb.append("class='block'");
            }
            sb.append(">");
            Row row = null; // 兼容
            Cell cell = null; // 兼容

            int maxRowNum = 0;
            int maxColNum = 0;
            //遍历每一行
            for (int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; rowNum++) {
                row = sheet.getRow(rowNum);
                if (row == null) {
                    continue;
                }
                int lastColNum = row.getLastCellNum();
                for (int colNum = 0; colNum < lastColNum; colNum++) {
                    cell = row.getCell(colNum);
                    if (cell == null) { // 特殊情况 空白的单元格会返回null
                        continue;
                    }
                    String stringValue = getCellValue1(cell);
                    if (map1[0].containsKey(rowNum + "," + colNum)) {
                        map1[0].remove(rowNum + "," + colNum);
                        if(maxRowNum<rowNum) {
                            maxRowNum = rowNum;
                        }
                        if(maxColNum<colNum) {
                            maxColNum = colNum;
                        }
                    } else if (map1[1].containsKey(rowNum + "," + colNum)) {
                        map1[1].remove(rowNum + "," + colNum);
                        if(maxRowNum<rowNum) {
                            maxRowNum = rowNum;
                        }
                        if(maxColNum<colNum) {
                            maxColNum = colNum;
                        }
                        continue;
                    }
                    if (stringValue == null || "".equals(stringValue.trim())) {
                        continue;
                    }else {
                        if(maxRowNum<rowNum) {
                            maxRowNum = rowNum;
                        }
                        if(maxColNum<colNum) {
                            maxColNum = colNum;
                        }
                    }
                }
            }
            for (int rowNum = sheet.getFirstRowNum(); rowNum <= maxRowNum; rowNum++) {
                row = sheet.getRow(rowNum);
                if (row == null) {
                    sb.append("<tr><td ></td></tr>");
                    continue;
                }
                sb.append("<tr>");
                int lastColNum = row.getLastCellNum();
                for (int colNum = 0; colNum <= maxColNum; colNum++) {
                    cell = row.getCell(colNum);
                    if (cell == null) { // 特殊情况 空白的单元格会返回null
                        sb.append("<td> </td>");
                        continue;
                    }
                    String stringValue = getCellValue(cell);
                    if (map[0].containsKey(rowNum + "," + colNum)) {
                        String pointString = map[0].get(rowNum + "," + colNum);
                        map[0].remove(rowNum + "," + colNum);
                        int bottomeRow = Integer.valueOf(pointString.split(",")[0]);
                        int bottomeCol = Integer.valueOf(pointString.split(",")[1]);
                        int rowSpan = bottomeRow - rowNum + 1;
                        int colSpan = bottomeCol - colNum + 1;
                        sb.append("<td rowspan= '" + rowSpan + "' colspan= '" + colSpan + "' ");
                    } else if (map[1].containsKey(rowNum + "," + colNum)) {
                        map[1].remove(rowNum + "," + colNum);
                        continue;
                    } else {
                        sb.append("<td ");
                    }

                    // 判断是否需要样式
                    if (isWithStyle) {
                        dealExcelStyle(wb, sheet, cell, sb,stylemap);// 处理单元格样式
                    }

                    sb.append("><nobr>");
                    //如果单元格为空要判断该单元格是不是通过其他单元格计算得到的
                    if (stringValue == null || "".equals(stringValue.trim())) {
                        FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
                        if (evaluator.evaluate(cell) != null) {
                            //如果单元格的值是通过其他单元格计算来的,则通过单元格计算获取
                            String cellnumber = evaluator.evaluate(cell).getNumberValue() + "";
                            //如果单元格的值是小数,保留两位
                            if (null != cellnumber && cellnumber.contains(".")) {
                                String[] decimal = cellnumber.split("\\.");
                                if (decimal[1].length() > 2) {
                                    int num1 = decimal[1].charAt(0) - '0';
                                    int num2 = decimal[1].charAt(1) - '0';
                                    int num3 = decimal[1].charAt(2) - '0';
                                    if (num3 == 9) {
                                        num2 = 0;
                                    } else if (num3 >= 5) {
                                        num2 = num2 + 1;
                                    }
                                    cellnumber = decimal[0] + "." + num1 + num2;
                                }
                            }
                            stringValue = cellnumber;
                        }
                        sb.append(stringValue.replace(String.valueOf((char) 160), " "));
                    } else {
                        // 将ascii码为160的空格转换为html下的空格( )
                        sb.append(stringValue.replace(String.valueOf((char) 160), " "));
                    }
                    sb.append("</nobr></td>");
                }
                sb.append("</tr>");
            }
            sb.append("</table>");
        }
        ulsb.append("</ul>");
        return ulsb.toString()+sb.toString();
    }


    private static Map<String, String>[] getRowSpanColSpanMap(Sheet sheet) {
        Map<String, String> map0 = new HashMap<String, String>();
        Map<String, String> map1 = new HashMap<String, String>();
        int mergedNum = sheet.getNumMergedRegions();
        CellRangeAddress range = null;
        for (int i = 0; i < mergedNum; i++) {
            range = sheet.getMergedRegion(i);
            int topRow = range.getFirstRow();
            int topCol = range.getFirstColumn();
            int bottomRow = range.getLastRow();
            int bottomCol = range.getLastColumn();
            map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol);
            // System.out.println(topRow + "," + topCol + "," + bottomRow + "," +
            // bottomCol);
            int tempRow = topRow;
            while (tempRow <= bottomRow) {
                int tempCol = topCol;
                while (tempCol <= bottomCol) {
                    map1.put(tempRow + "," + tempCol, "");
                    tempCol++;
                }
                tempRow++;
            }
            map1.remove(topRow + "," + topCol);
        }
        Map[] map = { map0, map1 };
        return map;
    }

    private static String getCellValue1(Cell cell) {
        String result = new String();
        switch (cell.getCellType()) {
            case NUMERIC:// 数字类型
                result = "1";
                break;
            case STRING:// String类型
                result = "1";
                break;
            case BLANK:
                result = "";
                break;
            default:
                result = "";
                break;
        }
        return result;
    }

    /**
     * 获取表格单元格Cell内容
     *
     * @param cell
     * @return
     */
    private static String getCellValue(Cell cell) {
        String result = new String();
        switch (cell.getCellType()) {
            case NUMERIC:// 数字类型
                if (DateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
                    SimpleDateFormat sdf = null;
                    if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
                        sdf = new SimpleDateFormat("HH:mm");
                    } else {// 日期
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                    }
                    Date date = cell.getDateCellValue();
                    result = sdf.format(date);
                } else if (cell.getCellStyle().getDataFormat() == 58) {
                    // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    double value = cell.getNumericCellValue();
                    Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
                    result = sdf.format(date);
                } else {
                    double value = cell.getNumericCellValue();
                    CellStyle style = cell.getCellStyle();
                    DecimalFormat format = new DecimalFormat();
                    String temp = style.getDataFormatString();
                    // 单元格设置成常规
                    if (temp.equals("General")) {
                        format.applyPattern("#");
                    }
                    result = format.format(value);
                }
                break;
            case STRING:// String类型
                result = cell.getRichStringCellValue().toString();
                break;
            case BLANK:
                result = "";
                break;
            default:
                result = "";
                break;
        }
        return result;
    }

    /**
     * 处理表格样式
     *
     * @param wb
     * @param sheet
     * @param sb
     */
    private static void dealExcelStyle(Workbook wb, Sheet sheet, Cell cell, StringBuffer sb,Map<String,String> stylemap) {
        CellStyle cellStyle = cell.getCellStyle();
        if (cellStyle != null) {
            HorizontalAlignment alignment = cellStyle.getAlignment();
            // sb.append("align='" + convertAlignToHtml(alignment) + "' ");//单元格内容的水平对齐方式
            VerticalAlignment verticalAlignment = cellStyle.getVerticalAlignment();
            String _style = "vertical-align:"+convertVerticalAlignToHtml(verticalAlignment)+";";
            if (wb instanceof XSSFWorkbook) {
                XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
                //short boldWeight = xf.getBoldweight();
                short boldWeight = 400;
                String align = convertAlignToHtml(alignment);
                int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
                _style +="font-weight:" + boldWeight + ";font-size: " + xf.getFontHeight() / 2 + "%;width:" + columnWidth + "px;text-align:" + align + ";";

                XSSFColor xc = xf.getXSSFColor();
                if (xc != null && !"".equals(xc)) {
                    _style +="color:#" + xc.getARGBHex().substring(2) + ";";
                }

                XSSFColor bgColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
                if (bgColor != null && !"".equals(bgColor)) {
                    _style +="background-color:#" + bgColor.getARGBHex().substring(2) + ";"; // 背景颜色
                }
                _style +=getBorderStyle(0, cellStyle.getBorderTop().getCode(),((XSSFCellStyle) cellStyle).getTopBorderXSSFColor());
                _style +=getBorderStyle(1, cellStyle.getBorderRight().getCode(),((XSSFCellStyle) cellStyle).getRightBorderXSSFColor());
                _style +=getBorderStyle(2, cellStyle.getBorderBottom().getCode(),((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor());
                _style +=getBorderStyle(3, cellStyle.getBorderLeft().getCode(),((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor());
            } else if (wb instanceof HSSFWorkbook) {
                HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
                short boldWeight = hf.getFontHeight();
                short fontColor = hf.getColor();
                HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette(); // 类HSSFPalette用于求的颜色的国际标准形式
                HSSFColor hc = palette.getColor(fontColor);
                String align = convertAlignToHtml(alignment);
                int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
                _style +="font-weight:" + boldWeight + ";font-size: " + hf.getFontHeight() / 2 + "%;text-align:" + align + ";width:" + columnWidth + "px;";
                String fontColorStr = convertToStardColor(hc);
                if (fontColorStr != null && !"".equals(fontColorStr.trim())) {
                    _style +="color:" + fontColorStr + ";"; // 字体颜色
                }
                short bgColor = cellStyle.getFillForegroundColor();
                hc = palette.getColor(bgColor);
                String bgColorStr = convertToStardColor(hc);
                if (bgColorStr != null && !"".equals(bgColorStr.trim())) {
                    _style +="background-color:" + bgColorStr + ";"; // 背景颜色
                }
                _style +=getBorderStyle(palette, 0, cellStyle.getBorderTop().getCode(), cellStyle.getTopBorderColor());
                _style +=getBorderStyle(palette, 1, cellStyle.getBorderRight().getCode(), cellStyle.getRightBorderColor());
                _style +=getBorderStyle(palette, 3, cellStyle.getBorderLeft().getCode(), cellStyle.getLeftBorderColor());
                _style +=getBorderStyle(palette, 2, cellStyle.getBorderBottom().getCode(), cellStyle.getBottomBorderColor());
            }
            String calssname="";
            if(!stylemap.containsKey(_style)) {
                int count = stylemap.size();
                calssname = "td"+count;
                stylemap.put(_style, calssname);
            }else {
                calssname = stylemap.get(_style);
            }
            if(!"".equals(calssname)) {
                sb.append("class='"+calssname+"'");
            }
        }
    }

    /**
     * 单元格内容的水平对齐方式
     *
     * @param alignment
     * @return
     */
    private static String convertAlignToHtml(HorizontalAlignment alignment) {
        String align = "center";
        switch (alignment) {
            case LEFT:
                align = "left";
                break;
            case CENTER:
                align = "center";
                break;
            case RIGHT:
                align = "right";
                break;
            default:
                break;
        }
        return align;
    }

    /**
     * 单元格中内容的垂直排列方式
     *
     * @param verticalAlignment
     * @return
     */
    private static String convertVerticalAlignToHtml(VerticalAlignment verticalAlignment) {

        String valign = "middle";
        switch (verticalAlignment) {
            case BOTTOM:
                valign = "bottom";
                break;
            case CENTER:
                valign = "middle";
                break;
            case TOP:
                valign = "top";
                break;
            default:
                break;
        }
        return valign;
    }

    private static String convertToStardColor(HSSFColor hc) {
        StringBuffer sb = new StringBuffer("");
        if (hc != null) {
            if (HSSFColor.HSSFColorPredefined.AUTOMATIC.getIndex() == hc.getIndex()) {
                return null;
            }
            sb.append("#");
            for (int i = 0; i < hc.getTriplet().length; i++) {
                sb.append(fillWithZero(Integer.toHexString(hc.getTriplet()[i])));
            }
        }
        return sb.toString();
    }

    private static String fillWithZero(String str) {
        if (str != null && str.length() < 2) {
            return "0" + str;
        }
        return str;
    }

    static String[] bordesr = { "border-top:", "border-right:", "border-bottom:", "border-left:" };
    static String[] borderStyles = { "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ",
            "solid ", "solid", "solid", "solid", "solid", "solid" };

    private static String getBorderStyle(HSSFPalette palette, int b, short s, short t) {
        if (s == 0)
            return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
        String borderColorStr = convertToStardColor(palette.getColor(t));
        borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000" : borderColorStr;
        return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
    }

    private static String getBorderStyle(int b, short s, XSSFColor xc) {
        if (s == 0)
            return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
        if (xc != null && !"".equals(xc)) {
            String borderColorStr = xc.getARGBHex();// t.getARGBHex();
            borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000"
                    : borderColorStr.substring(2);
            return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
        }
        return "";
    }

    /*
     * @param content 生成的excel表格标签
     *
     * @param htmlPath 生成的html文件地址
     */
    private static void writeFile(String content, String htmlPath, Map<String,String> stylemap,String name) {
        File file2 = new File(htmlPath);
        StringBuilder sb = new StringBuilder();
        try {
            file2.createNewFile();// 创建文件
            sb.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>"+name+"</title><style type=\"text/css\">");
            sb.append("ul{list-style: none;max-width: calc(100%);padding: 0px;margin: 0px;overflow-x: scroll;white-space: nowrap;} ul li{padding: 3px 5px;display: inline-block;border-right: 1px solid #768893;} ul li.cur{color: #F59C25;} table{border-collapse:collapse;display:none;width:100%;} table.block{display: block;}");
            for(Map.Entry<String, String> entry : stylemap.entrySet()){
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
                sb.append(" ."+mapValue+"{"+mapKey+"}");
            }
            sb.append("</style><script>");
            sb.append("function changetab(i){var block = document.getElementsByClassName(\"block\");block[0].className = block[0].className.replace(\"block\",\"\");var cur = document.getElementsByClassName(\"cur\");cur[0].className = cur[0].className.replace(\"cur\",\"\");var curli = document.getElementById(\"li_\"+i);curli.className += ' cur';var curtable = document.getElementById(\"table_\"+i);curtable.className=' block';}");
            sb.append("</script></head><body>");
            sb.append("<div>");
            sb.append(content);
            sb.append("</div>");
            sb.append("</body></html>");
            FileUtils.write(file2, sb.toString(),"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeFile1(String content, String htmlPath, Map<String,String> stylemap,String name) {
        File file2 = new File(htmlPath);
        StringBuilder sb = new StringBuilder();
        try {
            file2.createNewFile();// 创建文件
            sb.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>"+name+"</title><style type=\"text/css\">");
            sb.append("ul{list-style: none;max-width: calc(100%);padding: 0px;margin: 0px;overflow-x: scroll;white-space: nowrap;} ul li{padding: 3px 5px;display: inline-block;border-right: 1px solid #768893;} ul li.cur{color: #F59C25;} table{border-collapse:collapse;width:100%;} td{border: solid #000000 1px; min-width: 200px;}");
            sb.append("</style></head><body>");
            sb.append("<div>");
            sb.append(content);
            sb.append("</div>");
            sb.append("</body></html>");
            FileUtils.write(file2, sb.toString(),"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
代码示例
    public static void main(String[] args) {
        String sourcepath = "D:\\myExcel.xlsx";
        String htmlPositon =  "D:\\测试.html";
        Excel2HtmlUtil.readExcelToHtml(sourcepath, htmlPositon, true, "xlsx", "测试");
    }

使用已工具包 如 aspose-cells

依赖
<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>https://repository.aspose.com/repo/</url>
</repository>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-cells</artifactId>
    <version>20.11</version>
</dependency>

代码示例

使用 Aspose.Cells 将 Excel 转换为 HTML 非常简单。只需加载 Excel 电子表格并将其保存为 HTML 文件。以下是将 Excel XLSX 文件转换为 HTML 的步骤。

  • 使用 Workbook 类加载 XLSX 文件。
  • 使用 Workbook.Save(String) 方法以 .html 扩展名保存文件。

以下代码示例展示了如何使用 Java 将 Excel 文件转换为 HTML。

// 加载 Excel 文件
Workbook workbook = new Workbook("workbook.xlsx");

// 另存为 Excel XLSX 文件
workbook.save("Excel-to-HTML.html"); 

3.使用模板生成

流程

1、准备模板(这里是以Excel转html为模板)

2、处理模板及对模板填充内容的工具类

3、修改发送邮件的代码

准备模板

  1. 用excel 画一个所需表格模板
    在这里插入图片描述
  2. 找一个在线 excel 转html 网站
    如:我用的是:Table在线布局工具(Excel转HTML)
    下载后,修改后缀名为.ftl

然后使用文本编辑器,稍作修改。

<tbody>
  <tr height="26"> 
   <td colspan="2" class="et23">统计周期</td> 
   <td colspan="5" class="et10"></td> 
  </tr> 
  <tr height="26"> 
   <td colspan="2" class="et10">合作方</td> 
   <td colspan="2" class="et6">微信</td> 
   <td colspan="3" class="et6">支付宝</td> 
  </tr> 
  <tr height="26"> 
   <td rowspan="7" class="et10">放款</td> 
   <td class="et11">申请笔数</td> 
   <td colspan="2" class="et6"></td> 
   <td colspan="3" class="et6"></td> 
  </tr> 
  <tr height="26"> 
   <td class="et11">通过笔数</td> 
   <td colspan="2" class="et6"></td> 
   <td colspan="3" class="et6"></td> 
  </tr> 
  <tr height="26"> 
   <td class="et11">拒绝笔数</td> 
   <td colspan="2" class="et6"></td> 
   <td colspan="3" class="et6"></td> 
  </tr> 
  <tr height="19"> 
   <td rowspan="4" class="et11">拒绝原因枚举</td> 
   <td colspan="2" rowspan="4" class="et6">${data.apay.msg}</td> 
   <td colspan="3" rowspan="4" class="et6">${data.bpay.msg}</td> 
  </tr> 
  <tr height="19"> 
  </tr> 
  <tr height="19"> 
  </tr> 
  <tr height="18"> 
  </tr> 
  <tr> 
   <td class="et2" rowspan="${data.maxLength+1} " >放款</td> 
   <td class="et8">放款计划</td> 
   <td class="et15">笔数</td> 
   <td class="et16">金额</td> 
   <td class="et8">放款计划</td> 
   <td class="et15">笔数</td> 
   <td class="et16">金额</td> 
  </tr> 
  <#list 0..(data.maxLength - 1) as i>
    <tr>
      <#if data.maxLength != 0>
        <td class="et7">${data.apay.apayLoanInfoList[i].a!''}</td>
        <td class="et15">${data.apay.apayLoanInfoList[i].b!''}</td>
        <td class="et14">${data.apay.apayLoanInfoList[i].c!''}</td>
        <td class="et7">${data.bpay.bpayLoanInfoList[i].a!''}</td>
        <td class="et16">${data.bpay.bpayLoanInfoList[i].b!''}</td>
        <td class="et14">${data.bpay.bpayLoanInfoList[i].c!''}</td>
      </#if> 
      <#if data.maxLength = 0>
        <td class="et7" ></td>
        <td class="et15"></td>
        <td class="et14"></td>
        <td class="et7" ></td>
        <td class="et16"></td>
        <td class="et14"></td>
      </#if> 
    </tr>
  </#list>
 </tbody>

工具类

package com.ajc.module.mail.util;


import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.xxl.job.core.util.FileUtil;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class GenerateHtmlContextUtil<T> {
    /**
     * 本地临时地址
     */
    private static String TEMP_PATCH;
    /**
     * ftl模板地址
     */
    private static String TEMPLATE_FTL_PATH;
    /**
     * 是否需要删除临时生成的html文件
     */
    private Boolean NEED_DELETE_HTML = true;

    private  T data;
    private static Configuration CONFIG =  new Configuration(Configuration.getVersion());

    public final static String SUFFIX_FTL = ".ftl";
    public final static String SUFFIX_HTML = ".html";


    /**
     * 设置模板地址和临时文件地址
     * @param uploadPatch
     * @param templateFtlPath
     * @param needDeleteHtml 是否需要删除生成的 html文件
     */
    public  GenerateHtmlContextUtil(String uploadPatch,String templateFtlPath,boolean needDeleteHtml) {
        TEMP_PATCH = uploadPatch;
        TEMPLATE_FTL_PATH = templateFtlPath;
        NEED_DELETE_HTML = needDeleteHtml;
    }


    /**
     * 构建静态html
     **
      * @description:
      * @author:  liuql
      * @date: 2024/4/8 
      * @param fileName 不包括后缀名  
      *        
      */
    
    public  void buildStaticHtml(T data, String fileName) throws Exception {
        Map<String, Object> map = new HashMap<>(32);
        map.put("templateFtlPath", TEMPLATE_FTL_PATH);
        map.put("name", fileName);
        map.put("data", data);
        /// 放入文件后缀名
        map.put("suffix", SUFFIX_HTML);
        /// 生成静态html
        writerStaticFile(map);
    }

    /**
     * 页面静态化方法
     *
     * @param map 页面元素
     * @throws Exception
     */
    public  void writerStaticFile(Map<String, Object> map) throws Exception {
        //静态化
        File file = new File(TEMPLATE_FTL_PATH);
        File parentDirectory = file.getParentFile();

        CONFIG.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
        FileTemplateLoader templateLoader=new FileTemplateLoader(new File(parentDirectory.getAbsolutePath()));

        CONFIG.setTemplateLoader(templateLoader);
        //获取模板
        Template temple = CONFIG.getTemplate(file.getName());
        //生成最终页面并写到文件
        Writer out = new OutputStreamWriter(new FileOutputStream(
                TEMP_PATCH + File.separator + map.get("name") + map.get("suffix")));
        try {
            //处理
            temple.process(map, out);
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    /**
     * 读取静态html页面
     *
     * @param fileName 名称
     * @return staticHtml.toString() 静态页面html字符串
     */
    public  String generateStaticHtml(String fileName) {
        StringBuilder staticHtml = new StringBuilder(2048);

        try {

            FileReader fr = new FileReader(TEMP_PATCH + File.separator + fileName +SUFFIX_HTML );
            BufferedReader br = new BufferedReader(fr);

            String content = "";

            while ((content = br.readLine()) != null) {
                staticHtml.append(content);
            }

        } catch (Exception e) {
            return "";
        }
        if (NEED_DELETE_HTML){
            FileUtil.deleteFile(TEMP_PATCH + File.separator + fileName +SUFFIX_HTML);
        }
        return staticHtml.toString();
    }
}

代码示例


GenerateHtmlContextUtil<Map<String ,Object>> generateHtmlContextUtil = new GenerateHtmlContextUtil<>(tempPath,templateFtlPath,false);
// "hhh" 是临时生成的 html文件名
generateHtmlContextUtil.buildStaticHtml(dataMap,"hhh");
String htmlString = generateHtmlContextUtil.generateStaticHtml("hhh").toString();

dataMap 的结构
在这里插入图片描述

这里要非常小心,如果字段取不到是会报错的

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一些Java发送包含表格的邮件的代码示例。 首先,您需要使用JavaMail API来发送邮件。以下是一个简单的示例代码,可以发送包含表格的HTML电子邮件。 ```java import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { public static void main(String [] args) { // 收件人电子邮件地址 String to = "[email protected]"; // 发件人电子邮件地址 String from = "[email protected]"; // 发件人电子邮件密码(如果需要验证) String password = "password"; // SMTP服务器地址 String host = "smtp.example.com"; // 创建邮件会话 Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { // 创建邮件对象 MimeMessage message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress(from)); // 设置收件人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置邮件主题 message.setSubject("Test Email"); // 创建邮件内容 String html = "<html><body><table border='1'><tr><th>Column 1</th><th>Column 2</th></tr><tr><td>Row 1, Column 1</td><td>Row 1, Column 2</td></tr><tr><td>Row 2, Column 1</td><td>Row 2, Column 2</td></tr></table></body></html>"; MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(html, "text/html"); // 设置邮件内容 Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); // 发送邮件 Transport.send(message); System.out.println("邮件已发送!"); } catch (MessagingException e) { e.printStackTrace(); } } } ``` 在上面的代码示例中,我们通过创建一个HTML表格来设置邮件内容,并将其放入MimeBodyPart中。然后,我们将MimeBodyPart添加到Multipart对象中,并将其设置为邮件内容。最后,我们使用Transport.send()方法发送邮件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值