导出Excel表格并下载

补充:合并单元格

sheet.mergeCells(起始单元格列坐标,起始单元格行坐标,结束单元格列坐标,结束单元格行坐标);

起始位坐标单元为(0,0)


sheet.mergeCells(0, 0, 2, 2);


sheet.mergeCells(3, 5, 3, 8);

1、页面方法和发起请求方式

/** 用户点击下载时调用download()方法即可 */
function download(){
        //去空格
        tableTitle=tableTitle.trim();
        var url="/report/download?tableTitle="+tableTitle+"&unit="+unit+"&searchId="+searchId +"&type="+tableType+
            "&stringDate="+stringDate +"&submitType="+submitType;
        //游览器打开一个新的选项卡发起请求
        window.open(getRootPath()+url);
    }
    /** 获取项目根路径 */
    function getRootPath(){
        //获取当前网址
        var curWwwPath=window.document.location.href;
        //获取主机地址之后的目录,
        var pathName=window.document.location.pathname;
        var pos=curWwwPath.indexOf(pathName);
        //获取主机地址,
        var localhostPaht=curWwwPath.substring(0,pos);
        //获取带"/"的项目名,
        var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
        return(localhostPaht+projectName);
    }

2、Controller层,接收前端发起的导出下载请求和参数

//导出报表并下载
    @RequestMapping(value="/download",produces="application/vnd.ms-excel")
    @ResponseBody
    public void download(HttpServletRequest request,HttpServletResponse response,
                                       String tableTitle,String unit, String searchId, String type, String stringDate, String submitType) throws ParseException, IOException, WriteException {
        //设置文件名
        String fileName =tableTitle+".xls";
        //设置文件临时存放的路径
        String filePath = request.getServletContext().getRealPath("/") + fileName;
        //这句是调用方法获取要导出的记录,被我封装成了Map对象
        Map<String,Object> findData=reportService.getSearchData(searchId,type,stringDate,submitType,1,40);
        //取出数据集,可直接获取记录的list集即可
        List<Report> reportList= (List<Report>) findData.get("data");
        //我写好了一个导出Excel并下载和删除文件的class类,调用类方法
      DownloadFile.exportDownload(request,response,fileName,tableTitle,unit,filePath,reportList);
    }

3、自己编写的下载类,我把方法写成了静态的所以可以直接以类名点方法的方式访问,否则需要实例化类后方能访问

package com.common.utils;

import com.entity.Report;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

public class DownloadFile {
    public static void exportDownload(HttpServletRequest request, HttpServletResponse response,
                                      String fileName,String tableTitle,String unit, String filePath, List<Report> dataList) throws IOException, WriteException {
        //导出创建Excel存储在服务器指定路径的本地磁盘
        writeToExcel(tableTitle,filePath,unit,dataList);
        //下载导出的Excel文件
        downloadFile(response, filePath,fileName);
        //删除临时存储的Excel文件
        deleteFile(filePath);
    }
    private static void writeToExcel(String tableTitle,String filePath,String unit,List<Report> sheetDatas) throws IOException, WriteException {
        File file = new File(filePath);
        if(!file.exists()){
            file.createNewFile();
        }
        OutputStream os = new FileOutputStream(file);
        //创建excel文件
        WritableWorkbook book = Workbook.createWorkbook(os);
        //设置表头样式
        WritableFont titleFont = new WritableFont(WritableFont.createFont("微软雅黑"),12,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.WHITE); // 定义格式 字体 下划线 斜体 粗体 颜色
        WritableCellFormat titleFormat = new WritableCellFormat(titleFont);
        titleFormat.setBackground(Colour.GRAY_50);
        titleFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
        //设置单元格样式
        WritableFont cellFont = new WritableFont(WritableFont.createFont("微软雅黑"),10,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
        String sheetName = "sheet1";
        //打开文件创建sheet
        WritableSheet sheet = book.createSheet(sheetName,0);
        sheet.getSettings().setDefaultColumnWidth(20);
        //去掉整个sheet中的网格线
//        sheet.getSettings().setShowGridLines(false);
        //sheet首行添加标题
        sheet.addCell(new Label(0,0,unit));
        sheet.addCell(new Label(1,0,"当前值"));
        sheet.addCell(new Label(2,0,"同比值"));
        sheet.addCell(new Label(3,0,"同比增幅"));
        sheet.addCell(new Label(4,0,"环比值"));
        sheet.addCell(new Label(5,0,"环比增幅"));
        int i=1;
        for(Report report:sheetDatas){
            //具体行数据的填充
            sheet.addCell(new Label(0,i,report.getLogDate().toString()));
            sheet.addCell(new Label(1,i,report.getValue()+""));
            sheet.addCell(new Label(2,i,report.getOther()+""));
            sheet.addCell(new Label(3,i,report.getOtherPercent()));
            sheet.addCell(new Label(4,i,report.getRing()+""));
            sheet.addCell(new Label(5,i,report.getRingPercent()));
            i++;
        }
        book.write();
        book.close();
        os.close();
    }

    private static void downloadFile(HttpServletResponse response,String inputFilePath,String outPutFileName) throws IOException {
        // 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.reset();
        response.setContentType("multipart/form-data");
        // 2.设置文件头:最后一个参数是设置下载文件名
        response.setHeader("Content-Disposition", "attachment;fileName="+java.net.URLEncoder.encode(outPutFileName, "UTF-8"));
        response.setContentType("application/vnd.ms-excel");
        ServletOutputStream out;
        File file = new File(inputFilePath);
        FileInputStream inputStream = new FileInputStream(file);//文件输入流,读取excle文件
        // 3.通过response获取ServletOutputStream对象
        out = response.getOutputStream();
        int b = 0;
        byte[] buffer = new byte[512];
        while (b != -1) { //当excle文件存在内容就一直读取,-1为内容为空
            b = inputStream.read(buffer);
            // 4.写到输出流(out)中
            if (buffer.length > 2048) {
                out.write(buffer, 0, b);
            } else {
                out.write(buffer, 0, buffer.length);
            }
        }
        inputStream.close();
        out.close();
        out.flush();
    }
    private static void deleteFile(String filePath){
        File file = new File(filePath);
        if(file.exists()){
            file.delete();
        }
    }
}

4、Maven的pom文件加入这个jxl才能使用WritableWorkbook生成Excel文件

<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
    <dependency>
      <groupId>net.sourceforge.jexcelapi</groupId>
      <artifactId>jxl</artifactId>
      <version>2.6.12</version>
    </dependency>

猜你喜欢

转载自blog.csdn.net/readyyy/article/details/83140823