1. 程式人生 > >Java中檔案匯出excel

Java中檔案匯出excel

首先是在HTML頁面中加上匯出按鈕:

 <div class="ibox-body">
     <div id="exampleToolbar" role="group">
           <button type="button" class="btn btn-info" onclick="exportExel()">
               <i class="fa fa-download" aria-hidden="true"></i>匯出excel
           </button>
     </div>
     <table id="analysisTable" data-mobile-responsive="true">
     </table>
</div>

然後在對應的js檔案中加上匯出:

function  exportExel() {
    window.location.href= prefix+"/export";
}

這就到了匯出層了,需要我們去controller層去實現介面

@Log("匯出")
	@GetMapping("/export")
	void export(@RequestParam Map<String, Object> params,HttpServletResponse response) {
		Query query = new Query(params);
		List<Analysis> analysisList = analysisService.list(query);
		//匯出操作
		FileUtil.exportExcel(analysisList,"系統資料分析","系統資料",Analysis.class,"定級系統.xls",response);
	}

這裡的系統資料分析,系統資料,定級分析,分別對應的是excel檔案中不同的sheet。

 List<Analysis> list(Map<String, Object> map);

然後是service的實現類:

 @Override
    public List<Analysis> list(Map<String, Object> map) {
        return analysisDao.list(map);
    }

後邊是dao層

  List<Analysis> list(Map<String, Object> map);

最後是xml層

<!--list-->
	<select id="list" resultType="com.bootdo.nsmp.domain.Analysis">

		select
		info.`id`,
		info.`dept_namee`,
		dpt.`principal_name`,
		dpt.`unit_type`,
		info.`sys_name`,
		info.`dept_name`,
		info.`begin_use_time`,
		gd.`pro_grade`,
		gd.`pro_time`,
		gd.`jug_res`,
		gd.`gov_res`,
		sd.name as dptName,
		pro.`name` as provinceName,
		c.`name` as cityName,
		a.`name` as areaName
		from depart as dpt
		left join info_sys as info on dpt.dept_namee = info.dept_namee
		left join grade as gd on gd.info_sys_id = info.id
		left join sys_dept as sd  on dpt.dept_namee = sd.dept_id
		left join province pro on dpt.province = pro.code_p
		left join city c on dpt.city = c.code_c
		left join area a on dpt.area = a.code_a

		<if test="offset != null and limit != null">
			limit ${offset}, ${limit}
		</if>
	</select>

然後是層層將結果返回,最後載入在表中。

總之,匯出excel檔案的原理就是首先拿著id去呼叫後端,去庫裡查詢,然後將查詢到的結果放在檔案中,然後下載下來。

是不是還引用了一個外掛,我不知道。有這麼個檔案可以用來參考。


<!DOCTYPE html>
<html>
 
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
 
    <body>
        <div class="tools">
            <button type="button" class="btn green" id="excell" onclick="method5('dataTable')">匯出考勤表格</button>
        </div>
 
        <table border="1" id="dataTable">
            <tr>
                <td>王婷111</td>
                <td>一見傾城333 </td>
            </tr>
            <tr>
                <td>祈澈姑娘222</td>
                <td>Python開發者交流平臺44</td>
            </tr>
            <tr>
                <td>wwwangting888</td>
                <td>13661725475</td>
            </tr>
        </table>
 
    </body>
    <script>
        //打印表格
        var idTmr;
 
        function getExplorer() {
            var explorer = window.navigator.userAgent;
            //ie  
            if(explorer.indexOf("MSIE") >= 0) {
                return 'ie';
            }
            //firefox  
            else if(explorer.indexOf("Firefox") >= 0) {
                return 'Firefox';
            }
            //Chrome  
            else if(explorer.indexOf("Chrome") >= 0) {
                return 'Chrome';
            }
            //Opera  
            else if(explorer.indexOf("Opera") >= 0) {
                return 'Opera';
            }
            //Safari  
            else if(explorer.indexOf("Safari") >= 0) {
                return 'Safari';
            }
        }
 
        function method5(tableid) {
            if(getExplorer() == 'ie') {
                var curTbl = document.getElementById(tableid);
                var oXL = new ActiveXObject("Excel.Application");
                var oWB = oXL.Workbooks.Add();
                var xlsheet = oWB.Worksheets(1);
                var sel = document.body.createTextRange();
                sel.moveToElementText(curTbl);
                sel.select();
                sel.execCommand("Copy");
                xlsheet.Paste();
                oXL.Visible = true;
 
                try {
                    var fname = oXL.Application.GetSaveAsFilename("Excel.xls",
                        "Excel Spreadsheets (*.xls), *.xls");
                } catch(e) {
                    print("Nested catch caught " + e);
                } finally {
                    oWB.SaveAs(fname);
                    oWB.Close(savechanges = false);
                    oXL.Quit();
                    oXL = null;
                    idTmr = window.setInterval("Cleanup();", 1);
                }
 
            } else {
                tableToExcel(tableid)
            }
        }
 
        function Cleanup() {
            window.clearInterval(idTmr);
            CollectGarbage();
        }
        var tableToExcel = (function() {
            var uri = 'data:application/vnd.ms-excel;base64,',
                template = '<html><head><meta charset="UTF-8"></head><body><table  border="1">{table}</table></body></html>',
                base64 = function(
                    s) {
                    return window.btoa(unescape(encodeURIComponent(s)))
                },
                format = function(s, c) {
                    return s.replace(/{(\w+)}/g, function(m, p) {
                        return c[p];
                    })
                }
            return function(table, name) {
                if(!table.nodeType)
                    table = document.getElementById(table)
                var ctx = {
                    worksheet: name || 'Worksheet',
                    table: table.innerHTML
                }
                window.location.href = uri + base64(format(template, ctx))
            }
        })()
    </script>
 
</html>

是的,我去驗證了,這個外掛檔案確實使用到了。

//打印表格
var idTmr;

function getExplorer() {
    var explorer = window.navigator.userAgent;
    //ie
    if(explorer.indexOf("MSIE") >= 0) {
        return 'ie';
    }
    //firefox
    else if(explorer.indexOf("Firefox") >= 0) {
        return 'Firefox';
    }
    //Chrome
    else if(explorer.indexOf("Chrome") >= 0) {
        return 'Chrome';
    }
    //Opera
    else if(explorer.indexOf("Opera") >= 0) {
        return 'Opera';
    }
    //Safari
    else if(explorer.indexOf("Safari") >= 0) {
        return 'Safari';
    }
}

function exportFile(tableid) {debugger
    if(getExplorer() == 'ie') {
        var curTbl = document.getElementById(tableid);
        var oXL = new ActiveXObject("Excel.Application");
        var oWB = oXL.Workbooks.Add();
        var xlsheet = oWB.Worksheets(1);
        var sel = document.body.createTextRange();
        sel.moveToElementText(curTbl);
        sel.select();
        sel.execCommand("Copy");
        xlsheet.Paste();
        oXL.Visible = true;

        try {
            var fname = oXL.Application.GetSaveAsFilename("Excel.xls",
                "Excel Spreadsheets (*.xls), *.xls");
        } catch(e) {
            print("Nested catch caught " + e);
        } finally {
            oWB.SaveAs(fname);
            oWB.Close(savechanges = false);
            oXL.Quit();
            oXL = null;
            idTmr = window.setInterval("Cleanup();", 1);
        }

    } else {
        tableToExcel(tableid)
    }
}

function Cleanup() {
    window.clearInterval(idTmr);
    CollectGarbage();
}
var tableToExcel = (function() {
    var uri = 'data:application/vnd.ms-excel;base64,',
        template = '<html><head><meta charset="UTF-8"></head><body><table  border="1">{table}</table></body></html>',
        base64 = function(
            s) {
            return window.btoa(unescape(encodeURIComponent(s)))
        },
        format = function(s, c) {
            return s.replace(/{(\w+)}/g, function(m, p) {
                return c[p];
            })
        }
    return function(table, name) {
        if(!table.nodeType)
            table = document.getElementById(table)
        var ctx = {
            worksheet: name || 'Worksheet',
            table: table.innerHTML
        }
        window.location.href = uri + base64(format(template, ctx))
    }
})()