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";

    }

各塊代碼的功能: 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章