springboot導出Excel報表


一.實現流程

1.添加POI 的相關jar包

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.1</version>
</dependency>

2.編寫服務接口

比如說你要通過Excel表導出用戶信息,你在用戶管理接口中添加一個導出用戶信息Excel報表的方法,采用分頁查詢的方式,可以傳入要導出數據的范圍,如需要導出全部,將頁數據調制很大即可,同時因為調用的是分頁查詢方法查詢數據,所以同樣支持傳入過濾字段進行數據過濾。SysUserService接口代碼:

/**
     * 生成用戶信息Excel文件
     * @param pageRequest 要導出的分頁查詢參數
     * @return
     */
    File createUserExcelFile(PageRequest pageRequest);

3.編寫服務實現

在用戶管理服務實現類中編寫實現代碼,生成Excel。SysUserServiceImpl實現類代碼:

@Override
    public File createUserExcelFile(PageRequest pageRequest) {
        PageResult pageResult = findPage(pageRequest);
        return createUserExcelFile(pageResult.getContent());
    }
    
    public static File createUserExcelFile(List<?> records) {
        if (records == null) {
            records = new ArrayList<>();
        }
        Workbook workbook = new XSSFWorkbook();
        //創建一個sheet,括號里可以輸入sheet名稱,默認為sheet0
        Sheet sheet = workbook.createSheet();
        Row row0 = sheet.createRow(0);
        int columnIndex = 0;
        row0.createCell(columnIndex).setCellValue("No");
        row0.createCell(++columnIndex).setCellValue("ID");
        row0.createCell(++columnIndex).setCellValue("用戶名");
        row0.createCell(++columnIndex).setCellValue("昵稱");
        row0.createCell(++columnIndex).setCellValue("機構");
        row0.createCell(++columnIndex).setCellValue("角色");
        row0.createCell(++columnIndex).setCellValue("郵箱");
        row0.createCell(++columnIndex).setCellValue("手機號");
        row0.createCell(++columnIndex).setCellValue("狀態");
        row0.createCell(++columnIndex).setCellValue("頭像");
        row0.createCell(++columnIndex).setCellValue("創建人");
        row0.createCell(++columnIndex).setCellValue("創建時間");
        row0.createCell(++columnIndex).setCellValue("最后更新人");
        row0.createCell(++columnIndex).setCellValue("最后更新時間");
        for (int i = 0; i < records.size(); i++) {
            SysUser user = (SysUser) records.get(i);
            Row row = sheet.createRow(i + 1);
            for (int j = 0; j < columnIndex + 1; j++) {
                row.createCell(j);
            }
            columnIndex = 0;
            row.getCell(columnIndex).setCellValue(i + 1);
            row.getCell(++columnIndex).setCellValue(user.getId());
            row.getCell(++columnIndex).setCellValue(user.getName());
            row.getCell(++columnIndex).setCellValue(user.getNickName());
            row.getCell(++columnIndex).setCellValue(user.getDeptName());
            row.getCell(++columnIndex).setCellValue(user.getRoleNames());
            row.getCell(++columnIndex).setCellValue(user.getEmail());
            row.getCell(++columnIndex).setCellValue(user.getStatus());
            row.getCell(++columnIndex).setCellValue(user.getAvatar());
            row.getCell(++columnIndex).setCellValue(user.getCreateBy());
            row.getCell(++columnIndex).setCellValue(DateTimeUtils.getDateTime(user.getCreateTime()));
            row.getCell(++columnIndex).setCellValue(user.getLastUpdateBy());
            row.getCell(++columnIndex).setCellValue(DateTimeUtils.getDateTime(user.getLastUpdateTime()));
        }
  //調用PoiUtils工具包
        return PoiUtils.createExcelFile(workbook, "download_user");
    }

4.編寫控制器

在用戶管理控制器類添加一個接口,並調用service獲取File,最終通過文件操作工具類將File下載到本地。SYSUserController類代碼:

@PostMapping(value="/exportExcelUser")
    public void exportExcelUser(@RequestBody PageRequest pageRequest, HttpServletResponse res) {
        File file = sysUserService.createUserExcelFile(pageRequest);
        FileUtils.downloadFile(res, file, file.getName());
    }

二.工具類文件

為了簡化代碼,前面代碼的實現封裝了一些工具類。

2.1 PoiUtils

在編寫服務的時候我們通過PoiUtils中的createExcelFile方法生成Excel文件。代碼:

/**
 * POI相關操作
 * @author Louis
 * @date Jan 14, 2019
 */
public class PoiUtils {

    /**
     * 生成Excel文件
     * @param workbook
     * @param fileName
     * @return
     */
    public static File createExcelFile(Workbook workbook, String fileName) {
        OutputStream stream = null;
        File file = null;
        try {
            //用了createTempFile,這是創建臨時文件,系統會自動給你的臨時文件編號,所以后面有號碼,你用createNewFile的話就完全按照你指定的名稱來了
            file = File.createTempFile(fileName, ".xlsx");
            stream = new FileOutputStream(file.getAbsoluteFile());
            workbook.write(stream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //這里調用了IO工具包控制開關
            IOUtils.closeQuietly(workbook);
            IOUtils.closeQuietly(stream);
        }
        return file;
    }
}

IOUtils

/**
 * IO相關工具類
 * @author Louis
 * @date Oct 29, 2018
 */
public class IOUtils {

    /**
     * 關閉對象,連接
     * @param closeable
     */
    public static void closeQuietly(final Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (final IOException ioe) {
            // ignore
        }
    }
}

2.2 FileUtils

在編寫導出接口的時候我們通過FileUtils中的downloadFile將Excel文件下載到本地。代碼:

/**
 * 文件相關操作
 * @author Louis
 * @date Jan 14, 2019
 */
public class FileUtils {

    /**
     * 下載文件
     * @param response
     * @param file
     * @param newFileName
     */
    public static void downloadFile(HttpServletResponse response, File file, String newFileName) {
        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(newFileName.getBytes("ISO-8859-1"), "UTF-8"));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            InputStream is = new FileInputStream(file.getAbsolutePath());
            BufferedInputStream bis = new BufferedInputStream(is);
            int length = 0;
            byte[] temp = new byte[1 * 1024 * 10];
            while ((length = bis.read(temp)) != -1) {
                bos.write(temp, 0, length);
            }
            bos.flush();
            bis.close();
            bos.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }










1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM