溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JQuery 中怎么利用Ajax 導出報表

發(fā)布時間:2021-06-18 17:29:46 來源:億速云 閱讀:363 作者:Leah 欄目:大數(shù)據(jù)

JQuery 中怎么利用Ajax 導出報表,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

利用Ajax發(fā)送Get請求

        js代碼

$.ajax({
            type: "GET",
            url: encodeURI("http://localhost:8080/a?dd=" + dayinList+"),
            beforeSend: function () {
            },
            success: function (msg) {
            },
            error: function () {
            }
        })

        后臺代碼

@RestController
public class LogDownloadApi { 


    @GetMapping("/a")
    public void cs(@RequestParam("dd") String aa){
        System.out.println(aa);
    }

}

利用Ajax發(fā)送POST請求

        js代碼

$.ajax({ 
      type : "POST", 
      url : "http://localhost:8080/logDownload", 
      data : JSON.stringify({
            logList : dayinList,//數(shù)據(jù)List
            logName : "logName"//數(shù)據(jù)String
        }), 
      contentType : "application/json", 
      dataType : "json", 
      success: function (msg) {
         //成功執(zhí)行
            },
      error: function () {
      //失敗執(zhí)行
            }
    });

        后臺代碼

@RestController
public class LogDownloadApi { 


@PostMapping("/logDownload")
    public void ajaxPost(@RequestBody  Map map){
        System.out.println(map);
    }


}

利用POST請求,導出報表

        js代碼

<button class="btn btn-primary pull-right" onclick="outputResult(' + id + ')">導出查詢結果</button>
 /*導出選擇,并下載*/
    function outputResult(str) {
        var logName=document.getElementById("logName").textContent;
        console.log(logName)
        var dayinList = [];
        var List = $(".checkbox" + str.id + ":checked");
        for (var i = 0; i < List.length; i++) {
            dayinList.push(List[i].value)
        }
        var xhr = new XMLHttpRequest();
        xhr.open('post', 'http://localhost:8080/logDownload', true);
        xhr.responseType = 'blob';
        xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
        xhr.onload = function () {
            if (this.status == 200) {
                var blob = this.response;
                var a = document.createElement('a');
                var url = window.URL.createObjectURL(blob);
                a.href = url;
                //設置文件名稱
                a.download = logName+'.xls';
                a.click();
            }
        };
        xhr.send(JSON.stringify({
            logList : dayinList,//數(shù)據(jù)源
            logName : logName//文件名
        }));
    }

        后臺POST方法

@RestController
public class LogDownloadApi {

    private final InputExcelService inputExcelService;

    public LogDownloadApi(InputExcelService inputExcelService) {
        this.inputExcelService = inputExcelService;
    }


    @PostMapping("/logDownload")
    public void aa(@RequestBody  Map map,
                   @Context HttpServletResponse response,
                   @Context HttpServletRequest request) {
        List list = (List) map.get("logList");
        String logName = (String) map.get("logName");
        String fileName = logName.substring(1, logName.length());
        try {
            inputExcelService.exportExcel(response, request, list, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
package com.yx.http.service;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gao on 2018/12/24.
 * 報表下載
 */
@Service
public class InputExcelService {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd-hh-mm-ss");


    /**
     * 創(chuàng)建報表
     *
     * @param response                           請求響應信息
     * @param request                            請求信息
     * @param logList                            日志數(shù)據(jù)結果
     * @param xlsName                            報表名稱
     * @throws Exception 拋出異常錯誤
     */
    public void exportExcel(HttpServletResponse response, HttpServletRequest request, List<String> logList, String xlsName)throws Exception{
        /*第一步創(chuàng)建workbook*/
        HSSFWorkbook wb = new HSSFWorkbook();
        /*給表格簿賦值*/
        HSSFSheet sheet = wb.createSheet("日志數(shù)據(jù)");
        /*設置打印頁面為水平居中*/
        sheet.setHorizontallyCenter(true);
        /*第三步創(chuàng)建行row:添加表頭0行*/
        HSSFRow row = sheet.createRow(0);
        /*創(chuàng)建表標題與列標題單元格格式*/
        HSSFCellStyle style = wb.createCellStyle();
        /*居中*/
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        /*下邊框*/
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        /*左邊框*/
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        /*上邊框*/
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        /*右邊框*/
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 16);
        style.setFont(font);

        /*創(chuàng)建表格內數(shù)據(jù)格式*/
        HSSFCellStyle styleCell = wb.createCellStyle();
        /*居中*/
        styleCell.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        /*下邊框*/
        styleCell.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        /*左邊框*/
        styleCell.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        /*上邊框*/
        styleCell.setBorderTop(HSSFCellStyle.BORDER_THIN);
        /*右邊框*/
        styleCell.setBorderRight(HSSFCellStyle.BORDER_THIN);
        HSSFFont fontCell = wb.createFont();
        fontCell.setFontHeightInPoints((short) 14);
        styleCell.setFont(fontCell);
        /*創(chuàng)建下標為0的單元格*/
        row = sheet.createRow(0);
        /*設定值  row.createCell列名*/
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("日志數(shù)據(jù)");
        cell.setCellStyle(style);
        for (int i = 0; i < 12; i++) {
            cell = row.createCell(i + 1);
            cell.setCellValue("");
            cell.setCellStyle(style);
        }
        /*起始行,結束行,起始列,結束列*/
        CellRangeAddress callRangeAddress = new CellRangeAddress(0, 0, 0, 12);
        sheet.addMergedRegion(callRangeAddress);
        /*創(chuàng)建下標為1行的單元格*/
        row = sheet.createRow(1);

        /*設定值*/
        cell = row.createCell(0);
        cell.setCellValue("序號");
        /*內容居中*/
        cell.setCellStyle(style);
        /*設定值*/
        cell = row.createCell(1);
        cell.setCellValue("日志數(shù)據(jù)");
        cell.setCellStyle(style);
        /*自適應寬度*/
        for (int i = 0; i <= 13; i++) {
            sheet.autoSizeColumn(i);
            sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 12 / 10);
        }
        /*第五步插入數(shù)據(jù)*/
        /*創(chuàng)建行(可在此for循環(huán)插入數(shù)據(jù) row = sheet.createRow(i + 2))*/
        for (int i = 0; i < logList.size(); i++) {
            row = sheet.createRow(2+i);
            //創(chuàng)建單元格并且添加數(shù)據(jù)
            cell = row.createCell(0);
            cell.setCellValue(i+1);
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue(logList.get(i));
            cell.setCellStyle(style);

        }
        String fileName = xlsName + ".xls";
        String rtn = "";

            fileName = URLEncoder.encode(fileName, "UTF8");

        String userAgent = request.getHeader("User-Agent");
        /*針對IE或者以IE為內核的瀏覽器:*/
        if (userAgent != null) {
            userAgent = userAgent.toLowerCase();
            /*IE瀏覽器,只能采用URLEncoder編碼*/
            if (userAgent.indexOf("msie") != -1) {
                rtn = "filename=\"" + fileName + "\"";
            }
            /*Opera瀏覽器只能采用filename**/
            else if (userAgent.indexOf("opera") != -1) {
                rtn = "filename*=UTF-8''" + fileName;
            }
            /*Safari瀏覽器,只能采用ISO編碼的中文輸出*/
            else if (userAgent.indexOf("safari") != -1) {
                try {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            /*Chrome瀏覽器,只能采用MimeUtility編碼或ISO編碼的中文輸出*/
//            else if (userAgent.indexOf("applewebkit") != -1) {
//                fileName = MimeUtility.encodeText(fileName, "UTF8", "B");
//                rtn = "filename=\"" + fileName + "\"";
//            }
            /* FireFox瀏覽器,可以使用MimeUtility或filename*或ISO編碼的中文輸出*/
            else if (userAgent.indexOf("mozilla") != -1) {
                rtn = "filename*=UTF-8''" + fileName;
            }
        }
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;" + rtn);
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = null;
            outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();

    }


    /**
     * 排序
     * @param list
     * @param orderByParams
     * @return
     */
    public static List<Map<String, Object>> listContainMapSortByStringAsc(List<Map<String, Object>> list, String orderByParams) {

        Collections.sort(list, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                /*name1是從你list里面拿出來的一個*/
                String name1 = o1.get(orderByParams).toString();
                /*name1是從你list里面拿出來的第二個name*/
                String name2 = o2.get(orderByParams).toString();
                return name1.compareTo(name2);
            }
        });
        return list;
    }

}

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI