SpringBoot文件下载(1)——生成下载

1).引入Excel工具类,在pom.xml中输入:

        <dependency>
            <groupId>com.sargeraswang.util</groupId>
            <artifactId>excel-util</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>

2).新建.Java文件:HandleFile

package com.tfjybj.rbac.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class HandleFile{

    /**
     * Excel内容设置
     *
     * @param excelMap
     */
    public static HSSFWorkbook createExcel(Map<String, Object> excelMap) {

        HSSFWorkbook workbook = new HSSFWorkbook();
        String sheetName = excelMap.get("sheetName").toString();
        HSSFSheet sheet = workbook.createSheet(sheetName);

        //只考虑一个sheet的情况
        HSSFRow row = sheet.createRow(0);
        //设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
        sheet.setColumnWidth(1, 12 * 256);
        sheet.setColumnWidth(3, 17 * 256);

        //表头设置为居中加粗
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setBold(true);
//        font.setBoldweight((short) 14);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setFont(font);
        //是否生成序号,序号从1开始
        boolean isSerial = (boolean) excelMap.get("isSerial");
        //获取表头列表
        List<String> headerList = (List<String>) excelMap.get("header");
        HSSFCell cell;

        //生成表头
        int headRow=0;
        if (isSerial){
            //设置第一个列为序号列
            cell = row.createCell(0);
            cell.setCellValue("序号");
            cell.setCellStyle(style);
            headRow = 1;

        }
        for (String header : headerList) {
            cell = row.createCell(headRow);
            cell.setCellValue(header);
            cell.setCellStyle(style);
            headRow++;
        }

        //往Excel中插入数据
        List<List<String>> data = (List<List<String>>) excelMap.get("data");

        int rowNum = 1;
        //需要生成序号
        if (isSerial){
            //表头字段包含序号一列
            int headSize = headerList.size() + 1;
            for (List<String> obj:data){
                HSSFRow currRow = sheet.createRow(rowNum);
                for (int i=1;i<headSize;i++){
                    currRow.createCell(0).setCellValue(rowNum);
                    currRow.createCell(i).setCellValue(obj.get(i-1));
                }
                rowNum++;
            }
            //无需生成序号
        }else{
            int headSize = headerList.size();
            for (List<String> obj:data){
                HSSFRow currRow = sheet.createRow(rowNum);
                for (int i=0;i<headSize;i++){
                    currRow.createCell(i).setCellValue(obj.get(i));
                }
                rowNum++;
            }
        }

        return workbook;
    }

    /**
     * 生成excel文件
     *
     * @param filename
     * @param workbook
     * @throws Exception
     */
    public static void buildExcelFile(String filename, HSSFWorkbook workbook) throws Exception {
        FileOutputStream fos = new FileOutputStream(filename);
        workbook.write(fos);
        fos.flush();
        fos.close();
    }

    /**
     * 浏览器下载excel
     *
     * @param filename
     * @param workbook
     * @param response
     * @throws Exception
     */
    public static void buildExcelDocument(String filename, HSSFWorkbook workbook, HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }


}

3).主要代码

@GetMapping(value = "/createExcel")
    public String createExcel(HttpServletResponse response) throws Exception {
        //定义excelMap,存放excel中的信息
        Map<String, Object> excelMap = new HashMap<>();
        // 1.设置Excel表头
        List<String> headerList = new ArrayList<>();
        headerList.add("user_code");
        headerList.add("姓名");
        headerList.add("邮件");
        headerList.add("手机号");
        excelMap.put("header", headerList);

        // 2.是否需要生成序号,序号从1开始(true-生成序号 false-不生成序)
        excelMap.put("isSerial", false);

        // 3.sheet名
        String sheetName = "用户信息表";
        excelMap.put("sheetName", sheetName);


        // 4.需要放入Excel中的数据
        List<User> rows = new ArrayList<>();
        // 实例化用户
        User tempUser = new User();
        // 给用户添加属性值
        tempUser.setUserCode("17716577777");
        tempUser.setName("张三");
        tempUser.setEmail("[email protected]");
        tempUser.setPhone("17712331222");
        rows.add(tempUser);

        List<List<String>> data = new ArrayList<>();

        for (User user : rows) {
            // 所有的数据顺序必须和表头一一对应
            // list存放每一行的数据(让所有的数据类型都转换成String,这样就无需担心Excel表格中数据不对)
            List<String> list = new ArrayList<>();
            list.add(String.valueOf(user.getUserCode()));
            list.add(String.valueOf(user.getName()));
            list.add(String.valueOf(user.getEmail()));
            list.add(String.valueOf(user.getPhone()));
            //data存放全部的数据
            data.add(list);
        }
        excelMap.put("data", data);

        //Excel文件内容设置
        HSSFWorkbook workbook = HandleFile.createExcel(excelMap);
        //文件名
        String fileName = "Excel.xls";

        //生成excel文件
        HandleFile.buildExcelFile(fileName, workbook);

        //浏览器下载excel
        HandleFile.buildExcelDocument(fileName, workbook, response);

        return "down excel";

    }

各块代码的功能: 

猜你喜欢

转载自blog.csdn.net/Ciel_Y/article/details/107027056