SpringBoot導出Excel實現

一、Excel導出概述

在開發中,有時候需要將數據導出為Excel格式,在Excel中進行查看、分析、匯總等操作。對於Java Web開發者而言,一款好用的Excel導出插件是必不可少的。在SpringBoot中,我們可以使用EasyExcel、POI和JExcel等插件來實現Excel導出。

二、EasyExcel實現Excel導出

EasyExcel是基於POI封裝的一款Java解析和生成Excel的開源項目,具有高效、易用、功能強大的特點。EasyExcel支持大文件讀寫、百萬數據導出、快速生成Excel樣式等功能。下面介紹一下在SpringBoot中如何實現Excel導出。

1、引入EasyExcel依賴

我們可以通過在pom.xml文件中引入如下EasyExcel的maven依賴來使用EasyExcel插件:

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>easyexcel</artifactId>
        <version>2.1.6-beta5</version>
    </dependency>

2、定義實體類

假設我們要將一個人的信息導出為Excel表格,我們首先需要定義一個實體類:

    public class Person {
        private String name;
        private Integer age;
        private String email;
        //省略get、set方法
    }

3、創建ExcelWriter對象並寫入數據

接下來是最關鍵的一步,即創建ExcelWriter對象並寫入數據。我們可以通過如下代碼來實現:

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List list = new ArrayList();
        //省略添加數據操作
        String fileName = "person.xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("multipart/form-data");
        EasyExcel.write(response.getOutputStream(), Person.class).sheet("sheet").doWrite(list);
    }

4、代碼示例

下面是完整的Excel導出代碼示例,其中還包括了生成Excel樣式的操作:

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 數據準備
        List list = new ArrayList();
        Person person = new Person();
        person.setName("張三");
        person.setAge(20);
        person.setEmail("zhangsan@demo.com");
        list.add(person);

        // 生成Excel樣式
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 14);
        headWriteCellStyle.setWriteFont(headWriteFont);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontHeightInPoints((short) 12);
        contentWriteCellStyle.setWriteFont(contentWriteFont);

        // 寫入數據
        excelWriter.write(list, writeSheet, new TableWriteData(), new CellWriteData(headWriteCellStyle,contentWriteCellStyle));

        // 輸出Excel
        excelWriter.finish();
        response.setContentType("multipart/form-data");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("person.xlsx","UTF-8"));
    }

三、POI實現Excel導出

POI(Poor Obfuscation Implementation)是由Apache組織提供的用於操作Microsoft Office格式文件的Java API。下面介紹一下在SpringBoot中如何實現Excel導出。

1、引入POI依賴

我們可以通過在pom.xml文件中引入如下POI的maven依賴來使用POI插件:

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.0.1</version>
    </dependency>

2、創建Excel對象

接下來是最關鍵的一步,即創建Excel對象。我們可以通過如下代碼來實現:

    Workbook workbook = new XSSFWorkbook();//或者new HSSFWorkbook()
    Sheet sheet = workbook.createSheet("sheet");
    Row row = sheet.createRow(0);
    row.createCell(0).setCellValue("姓名");
    row.createCell(1).setCellValue("年齡");
    row.createCell(2).setCellValue("郵箱");

3、寫入數據並導出

我們可以通過如下代碼將數據寫入Excel中:

    int rowIndex = 1;
    for (Person person : list) {
        Row nRow = sheet.createRow(rowIndex++);
        nRow.createCell(0).setCellValue(person.getName());
        nRow.createCell(1).setCellValue(person.getAge());
        nRow.createCell(2).setCellValue(person.getEmail());
    }

接下來是導出的代碼:

    String fileName = "person.xlsx";
    response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
    workbook.write(response.getOutputStream());
    workbook.close();

4、代碼示例

下面是完整的Excel導出代碼示例:

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List list = new ArrayList();
        Person person = new Person();
        person.setName("張三");
        person.setAge(20);
        person.setEmail("zhangsan@demo.com");
        list.add(person);

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheet");
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("年齡");
        row.createCell(2).setCellValue("郵箱");
        int rowIndex = 1;
        for (Person person : list) {
            Row nRow = sheet.createRow(rowIndex++);
            nRow.createCell(0).setCellValue(person.getName());
            nRow.createCell(1).setCellValue(person.getAge());
            nRow.createCell(2).setCellValue(person.getEmail());
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("person.xlsx","UTF-8"));
        workbook.write(response.getOutputStream());
        workbook.close();
    }

四、JExcel實現Excel導出

JExcel是一款功能強大的Excel處理庫,支持Excel 97/2000/XP/2003格式,使用JExcel可以實現單元格樣式設置、單元格合併、單元格格式轉換以及數據寫入等功能。下面介紹一下在SpringBoot中如何實現Excel導出。

1、引入JExcel依賴

我們可以通過在pom.xml文件中引入如下JExcel的maven依賴來使用JExcel插件:

    <dependency>
        <groupId>net.sourceforge.jexcelapi</groupId>
        <artifactId>jxl</artifactId>
        <version>2.6.12</version>
    </dependency>

2、創建Excel對象

接下來是最關鍵的一步,即創建Excel對象。我們可以通過如下代碼來實現:

    WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
    WritableSheet sheet = workbook.createSheet("Sheet1", 0);
    Label label1 = new Label(0, 0, "姓名");
    Label label2 = new Label(1, 0, "年齡");
    Label label3 = new Label(2, 0, "郵箱");
    sheet.addCell(label1);
    sheet.addCell(label2);
    sheet.addCell(label3);

3、寫入數據並導出

我們可以通過如下代碼將數據寫入Excel中:

    int rowIndex = 1;
    for (Person person : list) {
        Label labelN1 = new Label(0, rowIndex, person.getName());
        Label labelN2 = new Label(1, rowIndex, person.getAge().toString());
        Label labelN3 = new Label(2, rowIndex, person.getEmail());
        sheet.addCell(labelN1);
        sheet.addCell(labelN2);
        sheet.addCell(labelN3);
        rowIndex++;
    }

接下來是導出的代碼:

    workbook.write();
    workbook.close();
    response.flushBuffer();

4、代碼示例

下面是完整的Excel導出代碼示例:

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List list = new ArrayList();
        Person person = new Person();
        person.setName("張三");
        person.setAge(20);
        person.setEmail("zhangsan@demo.com");
        list.add(person);

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("person.xls","UTF-8"));
        WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
        WritableSheet sheet = workbook.createSheet("Sheet1", 0);
        Label label1 = new Label(0, 0, "姓名");
        Label label2 = new Label(1, 0, "年齡");
        Label label3 = new Label(2, 0, "郵箱");
        sheet.addCell(label1);
        sheet.addCell(label2);
        sheet.addCell(label3);
        int rowIndex = 1;
        for (Person person : list) {
            Label labelN1 = new Label(0, rowIndex, person.getName());
            Label labelN2 = new Label(1, rowIndex, person.getAge().toString());
            Label labelN3 = new Label(2, rowIndex, person.getEmail());
            sheet.addCell(labelN1);
            sheet.addCell(labelN2);
            sheet.addCell(labelN3);
            rowIndex++;
        }

        workbook.write();
        workbook.close();
        response.flushBuffer();
    }

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/196886.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-03 13:26
下一篇 2024-12-03 13:26

相關推薦

  • 從ga角度解讀springboot

    springboot作為目前廣受歡迎的Java開發框架,其中的ga機制在整個開發過程中起著至關重要的作用。 一、ga是什麼 ga即Group Artifacts的縮寫,它是Mave…

    編程 2025-04-29
  • 為什麼不能用Microsoft Excel進行Python編程?

    Microsoft Excel是一個廣泛使用的數據分析工具,但是它不能直接用於Python編程。這是因為Microsoft Excel並不是一個編程工具,它的主要功能是進行數據處理…

    編程 2025-04-29
  • 基尼係數Excel計算模板

    這篇文章將介紹基尼係數Excel計算模板,為大家詳細闡述如何使用Excel進行基尼係數的計算。 一、模板下載及導入 首先需要下載基尼係數的Excel計算模板,可以在Excel中通過…

    編程 2025-04-28
  • SpringBoot Get方式請求傳參用法介紹

    本文將從以下多個方面對SpringBoot Get方式請求傳參做詳細的闡述,包括URL傳參、路徑傳參、請求頭傳參、請求體傳參等,幫助讀者更加深入地了解Get請求方式下傳參的相關知識…

    編程 2025-04-27
  • SpringBoot如何設置不輸出Info日誌

    本篇文章將帶您了解如何在SpringBoot項目中關閉Info級別日誌輸出。 一、為什麼要關閉Info日誌 在開發中,我們經常會使用Log4j、Logback等框架來輸出日誌信息,…

    編程 2025-04-27
  • 使用ReoGrid操作Excel的WPf應用

    本文將詳細闡述如何使用ReoGrid來操作Excel,重點介紹在WPF應用程序中使用ReoGrid的方法及注意點。 一、ReoGrid簡介 ReoGrid是一個基於.NET的開源組…

    編程 2025-04-27
  • 解決springboot中scanBasePackages無法讀取子包的問題

    在使用springboot搭建項目時,可能會遇到scanBasePackages無法讀取子包的問題。本文將從幾個方面詳細闡述如何解決這個問題。 一、問題描述 在使用Springbo…

    編程 2025-04-25
  • Excel日期函數

    Excel是當前企業和個人使用非常廣泛的辦公軟體之一。其中的日期函數可以用於處理各種涉及日期和時間的任務。本文將從不同的方面介紹Excel日期函數,幫助讀者深入了解和熟練使用日期函…

    編程 2025-04-25
  • SpringBoot請求參數綁定

    解答:SpringBoot請求參數綁定是指將HTTP請求中的參數與Controller方法的參數綁定起來,使得參數的傳遞變得簡單和方便。下面我們將從多個方面對SpringBoot請…

    編程 2025-04-25
  • Java Excel導入導出詳解

    一、Excel文件簡介 Excel是微軟公司開發的一種電子表格程序,多用於商業、財務、科學等各種數據處理。 Excel文件通常以.xls或.xlsx格式存儲,其中.xls格式為Ex…

    編程 2025-04-25

發表回復

登錄後才能評論