美文网首页
JS导出table到Excel

JS导出table到Excel

作者: bboymonk | 来源:发表于2017-08-30 13:24 被阅读0次

    这里有4个title对应4个table,点击导出Excel时,会根据每个导航传来的index进行switch匹配。

    下面是整个页面所有代码,angularjs jquery js混用。

    <#include "../common/head.html"/>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
    <body ng-app="goods" ng-controller="goodsCtrl"  >
    <div class="row-fluid">
        <div class="span12">
            <div class="control-group form-inline" style="border: 1px solid #ccc;padding: 10px; border-radius: 3px;">
    
    
                <div class="form-group">
                    <input ng-model="startTime" style="margin-top: 8px" readonly class="form-control layer-date" id="startDate"
                           placeholder="开始时间">
                    <label style="margin-top: -3px" class="laydate-icon inline demoicon"
                           onclick="laydate({elem: '#startDate',format:'YYYY-MM-DD hh:mm:ss',istime:true,istoday:false});"></label>
    
                    <input ng-model="endTime" style="margin-top: 8px" readonly class="form-control layer-date" id="endDate"
                           placeholder="结束时间">
                    <label style="margin-top: -3px" class="laydate-icon inline demoicon"
                           onclick="laydate({elem: '#endDate',format:'YYYY-MM-DD hh:mm:ss',istime:true,istoday:false});"></label>
    
                </div>
    
    
    
                <button ng-click="query()" id="btn_search" type="button" class="btn btn-primary btn-sm"
                        style="margin-left: 20px">
                    <span class="glyphicon glyphicon-search" aria-hidden="true"></span>查询
                </button>
                <button id="btn_clean_search"  type="button" class="btn btn-danger btn-sm">清空条件</button>
                <button ng-click="toExcel('homeExcel','inExcel','outExcel','totalExcel')" type="button" class="btn btn-info btn-sm">导出Excel</button>
            </div>
        </div>
    </div>
    
    <ul id="myTab" class="nav nav-tabs">
        <li id="homeClick" class="active" ng-click="refresh(0)">
            <a href="#home" data-toggle="tab">
                交易统计
            </a>
        </li>
        <li ng-click="refresh(1)">
            <a href="#in" data-toggle="tab">
                入库统计
            </a>
        </li>
        <li  ng-click="refresh(2)">
            <a href="#out" data-toggle="tab">
                出库统计
            </a>
        </li>
        <li   ng-click="refresh(3)">
            <a href="#total" data-toggle="tab">
                总库存
            </a>
        </li>
    </ul>
    
    
    <div id="myTabContent" class="tab-content">
        <div class="tab-pane fade in active" id="home">
            <table id="homeExcel" class="table table-bordered">
                <thead>
                <tr>
                    <th>游戏名称</th>
                    <th>道具名称</th>
                    <th>交易次数</th>
                    <th>单价</th>
                    <th>交易总额</th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="x in transaction">
                    <td>{{x.bundleName}}</td>
                    <td>{{x.productName}}</td>
                    <td>{{x.count}}</td>
                    <td>{{}}</td>
                    <td>{{}}</td>
                </tr>
                </tbody>
            </table>
    
        </div>
        <div class="tab-pane fade" id="in">
            <table id="inExcel" class="table table-bordered">
                <thead>
                <tr>
                    <th>操作人</th>
                    <th>游戏名称</th>
                    <th>道具名称</th>
                    <th>入库个数</th>
                    <th>单价</th>
                    <th>入库总额</th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="x in in">
                    <td>{{x.producerName}}</td>
                    <td>{{x.bundleName}}</td>
                    <td>{{x.productName}}</td>
                    <td>{{x.count}}</td>
                    <td>{{}}</td>
                    <td>{{}}</td>
                </tr>
                <tr ng-repeat="x in in2" style="color: red">
                    <td>操作人 &nbsp&nbsp&nbsp        {{x.producerName}}</td>
                    <td>总入库 &nbsp&nbsp&nbsp        ¥{{x.inPrice}}</td>
                </tr>
                <tr>
                    <td style="color: red">总计: &nbsp&nbsp&nbsp        ¥{{inPrice}}</td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="tab-pane fade" id="out">
            <table id="outExcel" class="table table-bordered">
                <thead>
                <tr>
                    <th>操作人</th>
                    <th>游戏名称</th>
                    <th>道具名称</th>
                    <th>交易次数</th>
                    <th>单价</th>
                    <th>交易总额</th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="x in out">
                    <td>{{x.consumerName}}</td>
                    <td>{{x.bundleName}}</td>
                    <td>{{x.productName}}</td>
                    <td>{{x.count}}</td>
                    <td>{{}}</td>
                    <td>{{}}</td>
                </tr>
                <tr ng-repeat="x in out2" style="color: red">
                    <td>操作人 &nbsp&nbsp&nbsp        {{x.consumerName}}</td>
                    <td>总入库 &nbsp&nbsp&nbsp        ¥{{x.outPrice}}</td>
                </tr>
                <tr>
                    <td style="color: red">总计: &nbsp&nbsp&nbsp        ¥{{outPrice}}</td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="tab-pane fade" id="total">
            <table id="totalExcel" class="table table-bordered">
                <thead>
                <tr>
                    <th>游戏名称</th>
                    <th>库存总价值</th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="x in total">
                    <td>{{x.bundleName}}</td>
                    <td>{{x.totalPrice}}元</td>
                </tr>
                <tr>
                    <td style="color: red">总计: &nbsp&nbsp&nbsp        ¥{{totalPrice}}</td>
                </tr>
                </tbody>
            </table>
    
        </div>
    
    </div>
    <script>
        angular.module('goods',[]).controller('goodsCtrl',function($scope, $http) {
            $scope.index = null;
            $http.get("/goods/transaction").then(function(response){
                $scope.transaction=response.data;
            });
            $http.get("/goods/in").then(function(response){
                $scope.in=response.data;
            });
            $http.get("/goods/inPrice").then(function(response){
                $scope.in2=response.data;
                $scope.inPrice = 0;
                angular.forEach($scope.in2, function(data){
                    $scope.inPrice+=data.inPrice;
                });
            });
            $http.get("/goods/out").then(function(response){
                $scope.out=response.data;
            });
            $http.get("/goods/outPrice").then(function(response){
                $scope.out2=response.data;
                $scope.outPrice = 0;
                angular.forEach($scope.out2, function(data){
                    $scope.outPrice+=data.outPrice;
                });
            });
            $http.get("/goods/total").then(function(response){
                $scope.total=response.data;
                $scope.totalPrice=0;
                angular.forEach($scope.total, function(data){
                    $scope.totalPrice+=data.totalPrice;
                });
            });
            /*根据时间查询*/
            $scope.query=function(){
                var start = $("#startDate").val();
                var end = $("#endDate").val();
                switch ($scope.index){
                    case 0:
                        $http.get("/goods/transaction?startTime="+start+"&endTime="+end).then(function(response){
                            $scope.transaction=response.data;
                        });
                        break
                    case 1:
                        $http.get("/goods/in?startTime="+start+"&endTime="+end).then(function(response){
                            $scope.in=response.data;
                        });
                        break
                    case 2:
                        $http.get("/goods/out?startTime="+start+"&endTime="+end).then(function(response){
                            $scope.out=response.data;
                        });
                        break
                    case 3:
    
                        break
                }
            };
    
    
    
            //刷新页面
            $scope.refresh=function(index) {
                $('#startDate').val("");
                $('#endDate').val("");
                $scope.index = index;
            }
            $(function(){
                $("#homeClick").click();
            });
            //清空条件按钮点击事件
            $("#btn_clean_search").on("click", function () {
                $('#startDate').val("");
                $('#endDate').val("");
                refresh();
            });
    
    //     *******************************导出excel***********************
            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';
                }
            }
            $scope.toExcel=function(homeExcel,inExcel,outExcel,totalExcel) {
                alert($scope.index);
                switch ($scope.index){
                    case 0:
                        if(getExplorer()=='ie')
                        {
                            var homeTbl = document.getElementById(homeExcel);
                            var oXL = new ActiveXObject("Excel.Application");
                            var oWB = oXL.Workbooks.Add();
                            var xlsheet = oWB.Worksheets(1);
                            var sel = document.body.createTextRange();
                            sel.moveToElementText(homeTbl);
                            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(homeExcel)
                        }
                        break
                    case 1:
                        if(getExplorer()=='ie')
                        {
                            var inTbl = document.getElementById(inExcel);
                            var oXL = new ActiveXObject("Excel.Application");
                            var oWB = oXL.Workbooks.Add();
                            var xlsheet = oWB.Worksheets(1);
                            var sel = document.body.createTextRange();
                            sel.moveToElementText(inTbl);
                            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(inExcel)
                        }
                        break
                    case 2:
                        if(getExplorer()=='ie')
                        {
                            var outTbl = document.getElementById(outExcel);
                            var oXL = new ActiveXObject("Excel.Application");
                            var oWB = oXL.Workbooks.Add();
                            var xlsheet = oWB.Worksheets(1);
                            var sel = document.body.createTextRange();
                            sel.moveToElementText(outTbl);
                            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(outExcel)
                        }
                        break
                    case 3:
                        if(getExplorer()=='ie')
                        {
                            var totalTbl = document.getElementById(totalExcel);
                            var oXL = new ActiveXObject("Excel.Application");
                            var oWB = oXL.Workbooks.Add();
                            var xlsheet = oWB.Worksheets(1);
                            var sel = document.body.createTextRange();
                            sel.moveToElementText(totalTbl);
                            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(totalExcel)
                        }
                        break
                }
            }
            function Cleanup() {
                window.clearInterval(idTmr);
                CollectGarbage();
            }
            var tableToExcel = (function() {
                this.tableBorder=1;
                var uri = 'data:application/vnd.ms-excel;base64,',
                    template = '<html><head><meta charset="UTF-8"></head><body><table>{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>
    
    </body>
    </html>
    

    下面是用JAVA POI实现导出到excel

    controller

    package com.apply.controller;
    
    import com.apply.model.Goods;
    import com.apply.service.GoodsService;
    import com.mysql.jdbc.StringUtils;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    
    /**
     * Created by Administrator on 2017/8/29.
     */
    @Controller
    @RequestMapping("goods")
    public class GoodsController {
        @GetMapping("statistics")
        public String statisticsGoods(){
            return "goods/statisticsGoods";
        }
    
        @Autowired
        private GoodsService goodsService;
        /**
         * 入库统计
         * @param startTime
         * @param endTime
         * @return
         * @throws ParseException
         */
        @ResponseBody
        @GetMapping("in")
        public List<Goods> inGoods(String startTime, String endTime) throws ParseException {
            Date start = null;
            Date end = null;
            if (!StringUtils.isNullOrEmpty(startTime) && !StringUtils.isNullOrEmpty(endTime)){
                start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime);
                end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);
            }
            List<Goods> list = goodsService.inGoods(start, end);
            for (int i = 0;i<list.size();i++){
                Integer count = goodsService.getCount(list.get(i).getProductName());
                list.get(i).setCount(count);
            }
            return list;
        }
    
        @ResponseBody
        @GetMapping("inPrice")
        public List<Goods> inPrice(){
            return goodsService.inPrice();
        }
    
        @ResponseBody
        @GetMapping("outPrice")
        public List<Goods> outPrice(){
            return goodsService.getOutPrice();
        }
    
        /**
         * 出库统计
         * @param startTime
         * @param endTime
         * @return
         * @throws ParseException
         */
        @ResponseBody
        @GetMapping("out")
        public List<Goods> outGoods(String startTime, String endTime) throws ParseException {
            Date start = null;
            Date end = null;
            if (!StringUtils.isNullOrEmpty(startTime) && !StringUtils.isNullOrEmpty(endTime)){
                start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime);
                end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);
            }
            List<Goods> list = goodsService.outGoods(start, end);
            for (int i = 0;i<list.size();i++){
                Integer count = goodsService.getOutCount(list.get(i).getProductName());
                list.get(i).setCount(count);
            }
            return list;
        }
    
        /**
         * 交易统计
         * @param startTime
         * @param endTime
         * @return
         * @throws ParseException
         */
        @ResponseBody
        @GetMapping("transaction")
        public List<Goods> transactionGoods(String startTime, String endTime) throws ParseException {
            Date start = null;
            Date end = null;
            if (!StringUtils.isNullOrEmpty(startTime) && !StringUtils.isNullOrEmpty(endTime)){
                start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime);
                end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);
            }
            List<Goods> list = goodsService.transactionGoods(start, end);
            for (int i = 0;i<list.size();i++){
                Integer count = goodsService.transactionCount(list.get(i).getProductName());
                list.get(i).setCount(count);
            }
            return list;
        }
        /**
         * 总库存
         * @return
         * @throws ParseException
         */
        @ResponseBody
        @GetMapping("total")
        public List<Goods> totalGoods(){
            return goodsService.totalGoods();
        }
    
        /**
         * excel导出
         */
        @GetMapping(value = "toExcel",produces = {"application/json"})
        public void exportExcel(HttpServletResponse response,Integer index) throws IOException {
            switch (index){
                case 0:
                    List<Goods> list = goodsService.transactionGoods(null, null);
                    for (int i = 0;i<list.size();i++){
                        Integer count = goodsService.transactionCount(list.get(i).getProductName());
                        list.get(i).setCount(count);
                    }
                    HSSFWorkbook wb = goodsService.export(list,null,index);
                    response.setContentType("application/vnd.ms-excel");
                    response.setHeader("Content-disposition", "attachment;filename=transactionGoods.xls");
                    OutputStream ouputStream = response.getOutputStream();
                    wb.write(ouputStream);
                    ouputStream.flush();
                    ouputStream.close();
                    break;
                case 1:
                    List<Goods> list1 = goodsService.inGoods(null, null);
                    for (int i = 0;i<list1.size();i++){
                        Integer count = goodsService.getCount(list1.get(i).getProductName());
                        list1.get(i).setCount(count);
                    }
                    List<Goods> innerList1 = goodsService.inPrice();  //table页面最下面的汇总,另行计算
                    HSSFWorkbook wb1 = goodsService.export(list1,innerList1,index);
                    response.setContentType("application/vnd.ms-excel");
                    response.setHeader("Content-disposition", "attachment;filename=inGoods.xls");
                    OutputStream ouputStream1 = response.getOutputStream();
                    wb1.write(ouputStream1);
                    ouputStream1.flush();
                    ouputStream1.close();
                    break;
                case 2:
                    List<Goods> list2 = goodsService.outGoods(null, null);
                    for (int i = 0;i<list2.size();i++){
                        Integer count = goodsService.getOutCount(list2.get(i).getProductName());
                        list2.get(i).setCount(count);
                    }
                    List<Goods> innerList2 = goodsService.getOutPrice();//table页面最下面的汇总,另行计算
                    HSSFWorkbook wb2 = goodsService.export(list2,innerList2,index);
                    response.setContentType("application/vnd.ms-excel");
                    response.setHeader("Content-disposition", "attachment;filename=outGoods.xls");
                    OutputStream ouputStream2 = response.getOutputStream();
                    wb2.write(ouputStream2);
                    ouputStream2.flush();
                    ouputStream2.close();
                    break;
                case 3:
                    List<Goods> list3 = goodsService.totalGoods();
                    HSSFWorkbook wb3 = goodsService.export(list3,null,index);
                    response.setContentType("application/vnd.ms-excel");
                    response.setHeader("Content-disposition", "attachment;filename=totalGoods.xls");
                    OutputStream ouputStream3 = response.getOutputStream();
                    wb3.write(ouputStream3);
                    ouputStream3.flush();
                    ouputStream3.close();
                    break;
            }
    
        }
    }
    

    service

    package com.apply.service;
    
    import com.apply.mapper.GoodsMapper;
    import com.apply.model.Goods;
    import org.apache.poi.hssf.usermodel.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.io.IOException;
    import java.util.Date;
    import java.util.List;
    
    /**
     * Created by Administrator on 2017/8/29.
     */
    @Service
    public class GoodsService {
        @Autowired
        private GoodsMapper goodsMapper;
    
        /**
         * 入库
         * @param startTime
         * @param endTime
         * @return
         */
        public List<Goods> inGoods(Date startTime, Date endTime){
            return goodsMapper.inGoods(startTime,endTime);
        }
    
        public Integer getCount(String product_name){
           return goodsMapper.getCount(product_name);
        }
    
        public List<Goods> inPrice(){
            return goodsMapper.getInPrice();
        }
        /**
         * 出库
         * @param startTime
         * @param endTime
         * @return
         */
        public List<Goods> outGoods(Date startTime, Date endTime){
            return goodsMapper.outGoods(startTime,endTime);
        }
        public Integer getOutCount(String product_name){
            return goodsMapper.getOutCount(product_name);
        }
        public List<Goods> getOutPrice(){
            return goodsMapper.getOutPrice();
        }
    
    
        /**
         * 交易
         * @param startTime
         * @param endTime
         * @return
         */
        public List<Goods> transactionGoods(Date startTime, Date endTime){
            return goodsMapper.transactionGoods(startTime,endTime);
        }
        public Integer transactionCount(String product_name){
            return goodsMapper.transactionCount(product_name);
        }
    
        /**
         * 总库存
         * @return
         */
        public List<Goods> totalGoods(){
            return goodsMapper.totalGoods();
        }
    
        /**
         * 导出excel
         * @param list
         * @return
         */
        public HSSFWorkbook export(List<Goods> list,List<Goods> innerList,Integer index) throws IOException {
            String[] excelHeader0 = { "游戏名称", "道具名称", "交易次数","单价","交易总额"};
            String[] excelHeader1 = { "操作人","游戏名称", "道具名称", "入库个数","单价","交易总额"};
            String[] excelHeader2 = { "操作人","游戏名称", "道具名称", "交易次数","单价","交易总额"};
            String[] excelHeader3 = { "游戏名称", "库存总价值"};
    
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = null;
            if(index == 0){
                sheet = wb.createSheet("交易统计");
            }else if (index ==1){
                sheet = wb.createSheet("入库统计");
            }else if (index ==2 ){
                sheet = wb.createSheet("出库统计");
            }else if (index ==3 ){
                sheet = wb.createSheet("总库存");
            }
            HSSFRow row = sheet.createRow((int) 0);
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    
            switch (index){
                case 0:
                    for (int i = 0; i < excelHeader0.length; i++) {
                        HSSFCell cell = row.createCell(i);
                        cell.setCellValue(excelHeader0[i]);
                        cell.setCellStyle(style);
                        sheet.setColumnWidth(i,excelHeader0[i].getBytes().length*2*256);
                    }
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.createRow(i + 1);
                        if (null != list.get(i).getBundleName()){
                            row.createCell(0).setCellValue(list.get(i).getBundleName());
                        }
                        if (null != list.get(i).getProductName()){
                            row.createCell(1).setCellValue(list.get(i).getProductName());
                        }
                        if (null != list.get(i).getCount()){
                            row.createCell(2).setCellValue(list.get(i).getCount());
                        }
                        if (null != list.get(i).getTransactionPrice()){
                            row.createCell(3).setCellValue(list.get(i).getTransactionPrice());
                        }
                        row.createCell(4).setCellValue("");
    
                    }
                    break;
                case 1:
                    for (int i = 0; i < excelHeader1.length; i++) {
                        HSSFCell cell = row.createCell(i);
                        cell.setCellValue(excelHeader1[i]);
                        cell.setCellStyle(style);
                        sheet.setColumnWidth(i,excelHeader1[i].getBytes().length*2*256);
                    }
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.createRow(i + 1);
                        if (null != list.get(i).getProducerName()){
                            row.createCell(0).setCellValue(list.get(i).getProducerName());
                        }
                        if (null != list.get(i).getBundleName()){
                            row.createCell(1).setCellValue(list.get(i).getBundleName());
                        }
                        if (null != list.get(i).getProductName()){
                            row.createCell(2).setCellValue(list.get(i).getProductName());
                        }
                        if (null != list.get(i).getCount()){
                            row.createCell(3).setCellValue(list.get(i).getCount());
                        }
                        if (null != list.get(i).getTransactionPrice()){
                            row.createCell(4).setCellValue(list.get(i).getTransactionPrice());
                        }
                        row.createCell(5).setCellValue("");
    
                    }
                    /*入库table下面的汇总*/
                    int inPrice = 0;
                    String ProducerName = "操作人";
                    String totalInGoods = "总入库   ¥";
                    String total = "总计: ¥";
                    for (int i = 0; i < innerList.size(); i++) {
                        inPrice += innerList.get(i).getInPrice();
                        row = sheet.createRow(list.size()+i+1);
                        if (null != innerList.get(i).getProducerName()){
                            row.createCell(0).setCellValue(ProducerName+innerList.get(i).getProducerName());
                        }
                        if (null != innerList.get(i).getInPrice()){
                            row.createCell(1).setCellValue(totalInGoods+innerList.get(i).getInPrice());
                        }
                    }
                    row = sheet.createRow(list.size()+innerList.size()+1);
                    row.createCell(0).setCellValue(total+inPrice);
                    break;
                case 2:
                    for (int i = 0; i < excelHeader2.length; i++) {
                        HSSFCell cell = row.createCell(i);
                        cell.setCellValue(excelHeader2[i]);
                        cell.setCellStyle(style);
                        sheet.setColumnWidth(i,excelHeader2[i].getBytes().length*2*256);
                    }
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.createRow(i + 1);
                        if (null != list.get(i).getConsumerName()){
                            row.createCell(0).setCellValue(list.get(i).getConsumerName());
                        }
                        if (null != list.get(i).getBundleName()){
                            row.createCell(1).setCellValue(list.get(i).getBundleName());
                        }
                        if (null != list.get(i).getProductName()){
                            row.createCell(2).setCellValue(list.get(i).getProductName());
                        }
                        if (null != list.get(i).getCount()){
                            row.createCell(3).setCellValue(list.get(i).getCount());
                        }
                        if (null != list.get(i).getTransactionPrice()){
                            row.createCell(4).setCellValue(list.get(i).getTransactionPrice());
                        }
                        row.createCell(5).setCellValue("");
                    }
                    /*出库table下面的汇总*/
                    int outPrice = 0;
                    String ConsumerName = "操作人";
                    String totalOutGoods = "总出库   ¥";
                    String total2 = "总计: ¥";
                    for (int i = 0; i < innerList.size(); i++) {
                        outPrice += innerList.get(i).getOutPrice();
                        row = sheet.createRow(list.size()+i+1);
                        if (null != innerList.get(i).getConsumerName()){
                            row.createCell(0).setCellValue(ConsumerName+innerList.get(i).getConsumerName());
                        }
                        if (null != innerList.get(i).getOutPrice()){
                            row.createCell(1).setCellValue(totalOutGoods+innerList.get(i).getOutPrice());
                        }
                    }
                    row = sheet.createRow(list.size()+innerList.size()+1);
                    row.createCell(0).setCellValue(total2+outPrice);
                    break;
                case 3:
                    for (int i = 0; i < excelHeader3.length; i++) {
                        HSSFCell cell = row.createCell(i);
                        cell.setCellValue(excelHeader3[i]);
                        cell.setCellStyle(style);
                        sheet.setColumnWidth(i,excelHeader3[i].getBytes().length*2*256);
                    }
                    /*总库存table下面的汇总*/
                    String total3 = "总计   ¥";
                    int totalPrice = 0;
                    for (int i = 0;i<list.size();i++){
                        totalPrice += list.get(i).getTotalPrice();
                        row = sheet.createRow(i + 1);
                        if (null != list.get(i).getBundleName()){
                            row.createCell(0).setCellValue(list.get(i).getBundleName());
                        }
                        if (null != list.get(i).getTotalPrice()){
                            row.createCell(1).setCellValue(list.get(i).getTotalPrice());
                        }
                    }
                    row = sheet.createRow(list.size()+1);
                    row.createCell(0).setCellValue(total3+totalPrice);
                    break;
            }
    
            return wb;
        }
    }
    

    JS

    $scope.toExcel=function(){
                alert($scope.index);
                switch ($scope.index){
                    case 0:
                        location.href="/goods/toExcel?index="+$scope.index;
                        break
                    case 1:
                        location.href="/goods/toExcel?index="+$scope.index;
                        break
                    case 2:
                        location.href="/goods/toExcel?index="+$scope.index;
                        break
                    case 3:
                        location.href="/goods/toExcel?index="+$scope.index;
                        break
                }
            }
    

    相关文章

      网友评论

          本文标题:JS导出table到Excel

          本文链接:https://www.haomeiwen.com/subject/hxhtjxtx.html