前端Table數據導出Excel使用HSSFWorkbook(Java)


 

一、實現原理:

1. 前端查詢列表數據並渲染至table(<table>...</table>)表格

2. 表格html代碼傳輸至后台

3. 后台把html轉成Excel輸出流返回前端

4. 前端自動調用下載器完成下載

注:因為渲染之后的hmtl代碼數據量有可能很大,因此要使用POST方式的form表單方式提交。

 

二、實現步驟:

1. 查詢后台數據並且渲染至頁面table在此忽略,直接用一下靜態html代替:

 <div id="table">
     <table id="targetTable">
         <thead>
             <tr>
                 <th style="background: fuchsia;">名次</th>
                 <th>姓名</th>
                 <th>成績</th>
             </tr>
         </thead>
         <tbody>
             <tr align="center">
                 <td>1</td>
                 <td>小明</td>
                 <td>100</td>
             </tr>
             <tr align="center">
                 <td>2</td>
                 <td>小紅</td>
                 <td>95.5</td>
             </tr>
         </tbody>
     </table>
 </div>

2. 表格html傳輸至后台進行解析生成excel輸出流:

<script language="JavaScript">

        function makeFormSubmit(url, excelName, tableHtml) {
            // 創建一個 form
            var form1 = document.createElement("form");
            // 添加到 body 中
            document.body.appendChild(form1);
            // 創建輸入
            var input = document.createElement("input");
            input.name = "excelName";
            input.value = excelName;
            var input1 = document.createElement("input");
            input1.name = "tableHtml";
            input1.value = tableHtml;
            // 將輸入框插入到 form 中
            form1.appendChild(input);
            form1.appendChild(input1);
            // form 的提交方式
            form1.method = "POST";
            // form 提交路徑
            form1.action = url;
       //以附件方式 解決數據量大的問題        
       form1.enctype = "multipart/form-data";
// 對該 form 執行提交 form1.submit(); // 刪除該 form document.body.removeChild(form1); } function loadExcel() { var tableHtml = document.getElementById('table').innerHTML; makeFormSubmit("/admin/api/excel/loadExcel", "測試excel", tableHtml); } </script>

完整的hmtl頁面代碼:

<html>
<head>
    <meta http-equiv="content-Type" content="text/html;charset=utf-8"/>
    <script src="./xqf-js/jquery.min.js"></script>
    <script language="JavaScript">

        function makeFormSubmit(url, excelName, tableHtml) {
            // 創建一個 form
            var form1 = document.createElement("form");
            // 添加到 body 中
            document.body.appendChild(form1);
            // 創建輸入
            var input = document.createElement("input");
            input.name = "excelName";
            input.value = excelName;
            var input1 = document.createElement("input");
            input1.name = "tableHtml";
            input1.value = tableHtml;
            // 將輸入框插入到 form 中
            form1.appendChild(input);
            form1.appendChild(input1);
            // form 的提交方式
            form1.method = "POST";
            // form 提交路徑
            form1.action = url;
       //以附件方式 解決數據量大的問題        
       form1.enctype = "multipart/form-data";
// 對該 form 執行提交 form1.submit(); // 刪除該 form document.body.removeChild(form1); } function loadExcel() { var tableHtml = document.getElementById('table').innerHTML; makeFormSubmit("/admin/api/excel/loadExcel", "測試excel", tableHtml); } </script> </head> <body> <div id="table"> <table id="targetTable"> <thead> <tr> <th style="background: fuchsia;">名次</th> <th>姓名</th> <th>成績</th> </tr> </thead> <tbody> <tr align="center"> <td>1</td> <td>小明</td> <td>100</td> </tr> <tr align="center"> <td>2</td> <td>小紅</td> <td>95.5</td> </tr> </tbody> </table> </div> <a href="javascript:" onclick="loadExcel();"> <input id="Button1" type="button" value="導出" /> </a> </body> </html>

3. 后台轉換代碼:

必要的jar包,maven項目所以直接pom導入:

<!-- Excel導出相關 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-examples</artifactId>
            <version>3.8</version>
        </dependency>

跨行元素元數據類:

package com.loanofficer.utils.excel;

/**
 * 跨行元素元數據
 *
 */
public class CrossRangeCellMeta {

    public CrossRangeCellMeta(int firstRowIndex, int firstColIndex, int rowSpan, int colSpan) {
        super();
        this.firstRowIndex = firstRowIndex;
        this.firstColIndex = firstColIndex;
        this.rowSpan = rowSpan;
        this.colSpan = colSpan;
    }

    private int firstRowIndex;
    private int firstColIndex;
    private int rowSpan;// 跨越行數
    private int colSpan;// 跨越列數

    int getFirstRow() {
        return firstRowIndex;
    }

    int getLastRow() {
        return firstRowIndex + rowSpan - 1;
    }

    int getFirstCol() {
        return firstColIndex;
    }

    int getLastCol() {
        return firstColIndex + colSpan - 1;
    }

    int getColSpan(){
        return colSpan;
    }
}

將html table 轉成 excel類:

package com.loanofficer.utils.excel;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 將html table 轉成 excel
 *
 * 記錄下來所占的行和列,然后填充合並
 */
public class ConvertHtml2Excel {
    /**
     * html表格轉excel
     *
     * @param tableHtml 如
     *            <table>
     *            ..
     *            </table>
     * @return
     */
    public static HSSFWorkbook table2Excel(String tableHtml) {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();

        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        List<CrossRangeCellMeta> crossRowEleMetaLs = new ArrayList<>();
        int rowIndex = 0;
        try {
            Document data = DocumentHelper.parseText(tableHtml);
            // 生成表頭
            Element thead = data.getRootElement().element("thead");
            HSSFCellStyle titleStyle = getTitleStyle(wb);
            if (thead != null) {
                List<Element> trLs = thead.elements("tr");
                for (Element trEle : trLs) {
                    HSSFRow row = sheet.createRow(rowIndex);
                    List<Element> thLs = trEle.elements("th");
                    makeRowCell(thLs, rowIndex, row, 0, titleStyle, crossRowEleMetaLs);
                    row.setHeightInPoints(17);
                    rowIndex++;
                }
            }
            // 生成表體
            Element tbody = data.getRootElement().element("tbody");
            if (tbody != null) {
                HSSFCellStyle contentStyle = getContentStyle(wb);
                List<Element> trLs = tbody.elements("tr");
                for (Element trEle : trLs) {
                    HSSFRow row = sheet.createRow(rowIndex);
                    List<Element> thLs = trEle.elements("th");
                    int cellIndex = makeRowCell(thLs, rowIndex, row, 0, titleStyle, crossRowEleMetaLs);
                    List<Element> tdLs = trEle.elements("td");
                    makeRowCell(tdLs, rowIndex, row, cellIndex, contentStyle, crossRowEleMetaLs);
                    row.setHeightInPoints(18);
                    rowIndex++;
                }
            }
            // 合並表頭
            for (CrossRangeCellMeta crcm : crossRowEleMetaLs) {
                sheet.addMergedRegion(new CellRangeAddress(crcm.getFirstRow(), crcm.getLastRow(), crcm.getFirstCol(), crcm.getLastCol()));
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //自動調整列寬
        for (int i = 0; i < 15; i++) {
            sheet.autoSizeColumn((short)i);
        }
        return wb;
    }

    /**
     * 生產行內容
     *
     * @return 最后一列的cell index
     */
    /**
     * @param tdLs th或者td集合
     * @param rowIndex 行號
     * @param row POI行對象
     * @param startCellIndex
     * @param cellStyle 樣式
     * @param crossRowEleMetaLs 跨行元數據集合
     * @return
     */
    private static int makeRowCell(List<Element> tdLs, int rowIndex, HSSFRow row, int startCellIndex, HSSFCellStyle cellStyle,
                                   List<CrossRangeCellMeta> crossRowEleMetaLs) {
        int i = startCellIndex;
        for (int eleIndex = 0; eleIndex < tdLs.size(); i++, eleIndex++) {
            int captureCellSize = getCaptureCellSize(rowIndex, i, crossRowEleMetaLs);
            while (captureCellSize > 0) {
                for (int j = 0; j < captureCellSize; j++) {// 當前行跨列處理(補單元格)
                    row.createCell(i);
                    i++;
                }
                captureCellSize = getCaptureCellSize(rowIndex, i, crossRowEleMetaLs);
            }
            Element thEle = tdLs.get(eleIndex);
            String val = thEle.getTextTrim();
            if (StringUtils.isBlank(val)) {
                Element e = thEle.element("a");
                if (e != null) {
                    val = e.getTextTrim();
                }
            }
            HSSFCell c = row.createCell(i);
            if (NumberUtils.isNumber(val)) {
                c.setCellValue(Double.parseDouble(val));
                c.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
            } else {
                c.setCellValue(val);
            }
            c.setCellStyle(cellStyle);
            int rowSpan = NumberUtils.toInt(thEle.attributeValue("rowspan"), 1);
            int colSpan = NumberUtils.toInt(thEle.attributeValue("colspan"), 1);
            if (rowSpan > 1 || colSpan > 1) { // 存在跨行或跨列
                crossRowEleMetaLs.add(new CrossRangeCellMeta(rowIndex, i, rowSpan, colSpan));
            }
            if (colSpan > 1) {// 當前行跨列處理(補單元格)
                for (int j = 1; j < colSpan; j++) {
                    i++;
                    row.createCell(i);
                }
            }
        }
        return i;
    }

    /**
     * 獲得因rowSpan占據的單元格
     *
     * @param rowIndex 行號
     * @param colIndex 列號
     * @param crossRowEleMetaLs 跨行列元數據
     * @return 當前行在某列需要占據單元格
     */
    private static int getCaptureCellSize(int rowIndex, int colIndex, List<CrossRangeCellMeta> crossRowEleMetaLs) {
        int captureCellSize = 0;
        for (CrossRangeCellMeta crossRangeCellMeta : crossRowEleMetaLs) {
            if (crossRangeCellMeta.getFirstRow() < rowIndex && crossRangeCellMeta.getLastRow() >= rowIndex) {
                if (crossRangeCellMeta.getFirstCol() <= colIndex && crossRangeCellMeta.getLastCol() >= colIndex) {
                    captureCellSize = crossRangeCellMeta.getLastCol() - colIndex + 1;
                }
            }
        }
        return captureCellSize;
    }

    /**
     * 獲得標題樣式
     *
     * @param workbook
     * @return
     */
    private static HSSFCellStyle getTitleStyle(HSSFWorkbook workbook) {
        short titlebackgroundcolor = HSSFColor.GREY_25_PERCENT.index;
        short fontSize = 12;
        String fontName = "宋體";
        HSSFCellStyle style = workbook.createCellStyle();
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setBorderBottom((short) 1);
        style.setBorderTop((short) 1);
        style.setBorderLeft((short) 1);
        style.setBorderRight((short) 1);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setFillForegroundColor(titlebackgroundcolor);// 背景色

        HSSFFont font = workbook.createFont();
        font.setFontName(fontName);
        font.setFontHeightInPoints(fontSize);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        style.setFont(font);
        return style;
    }

    /**
     * 獲得內容樣式
     *
     * @param wb
     * @return
     */
    private static HSSFCellStyle getContentStyle(HSSFWorkbook wb) {
        short fontSize = 12;
        String fontName = "宋體";
        HSSFCellStyle style = wb.createCellStyle();
        style.setBorderBottom((short) 1);
        style.setBorderTop((short) 1);
        style.setBorderLeft((short) 1);
        style.setBorderRight((short) 1);

        HSSFFont font = wb.createFont();
        font.setFontName(fontName);
        font.setFontHeightInPoints(fontSize);
        style.setFont(font);
        return style;
    }


    public static void main(String[] args) {

        String c = new String("<table id=\"targetTable\">\n" +
                "    <thead>\n" +
                "        <tr align=\"center\">\n" +
                "            <th>名次</th>\n" +
                "            <th>姓名</th>\n" +
                "            <th>成績</th>\n" +
                "        </tr>\n" +
                "    </thead>\n" +
                "    <tbody>\n" +
                "        <tr align=\"center\">\n" +
                "            <td>1</td>\n" +
                "            <td>小明</td>\n" +
                "            <td>100</td>\n" +
                "        </tr>\n" +
                "        <tr align=\"center\">\n" +
                "            <td>2</td>\n" +
                "            <td>小紅</td>\n" +
                "            <td>95.5</td>\n" +
                "        </tr>\n" +
                "    </tbody>\n" +
                "</table>");
        HSSFWorkbook wb = table2Excel(c);
        try {
            FileOutputStream fos = new FileOutputStream(new File("1.xls"));
            wb.write(fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Controller類:

package com.loanofficer.web.api;

import com.loanofficer.utils.excel.ConvertHtml2Excel;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@RequestMapping(value = "/api/excel")
public class ExcelController {

    @PostMapping(value = "/loadExcel")
    private void loadExcelGet(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 設置文件的mime類型
        resp.setContentType("application/vnd.ms-excel");

        // 存儲編碼后的文件名
        String excelName = "name";
        // 存儲文件名稱
        String n = req.getParameter("excelName");

        try {
            excelName = URLEncoder.encode(n, "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        resp.setHeader("content-disposition", "attachment;filename=" + excelName + ".xls;filename*=utf-8''" + excelName + ".xls");

        String tableHtml = req.getParameter("tableHtml");

        // 從session中刪除saveExcelMsg屬性
        req.getSession().removeAttribute("saveExcelMsg");
        // 定義一個輸出流
        ServletOutputStream sos = null;

        HSSFWorkbook wb = ConvertHtml2Excel.table2Excel(tableHtml);

        try {
            // 保存到文件中
            sos = resp.getOutputStream();
            wb.write(sos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sos != null) {
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM