Spring學習手冊 2:Spring MVC 導出excel表格

目錄php

完整代碼在這html

Spring 導出excel表格有不少種方法,能夠直接用設置文件頭的方法,也能夠使用ContentNegotiatingViewResolver 直接將excel文件直接解析成view。java

1、配置文件要加上哪些東西?

首先,若是採用設置響應頭的方式來導出excel文件,並不須要配置得很複雜,只要加上一個excel的處理庫和Java-servlet庫就能夠。在這裏,我使用了apache-poi庫。web

完整pom配置文件spring

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.learn.springmvc</groupId>
  <artifactId>SpringMVCExportFile</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SpringMVCExportFile Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.11.RELEASE</version>
    </dependency>

    <!--Excel 依賴包-->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.10-beta2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>3.0-alpha-1</version>
    </dependency>
  </dependencies>


  <build>
    <finalName>SpringMVCExportFile</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
複製代碼

2、依據poi包的用法建立一個用來導出excel文件的工具類:

package com.learn.com.learn.tool;

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

import javax.servlet.ServletOutputStream;

public class ExcelExport {
    public void export(String titles[], String datas[][], ServletOutputStream out) throws Exception{
        try{
            // 第一步,建立一個workbook,對應一個Excel文件
            HSSFWorkbook workbook = new HSSFWorkbook();

            // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet
            HSSFSheet hssfSheet = workbook.createSheet("sheet1");

            // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short

            HSSFRow row = hssfSheet.createRow(0);
            // 第四步,建立單元格,並設置值表頭 設置表頭居中
            HSSFCellStyle hssfCellStyle = workbook.createCellStyle();

            //居中樣式
            hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            HSSFCell hssfCell = null;
            for (int i = 0; i < titles.length; i++) {
                hssfCell = row.createCell(i);//列索引從0開始
                hssfCell.setCellValue(titles[i]);//列名1
                hssfCell.setCellStyle(hssfCellStyle);//列居中顯示
            }

            int lens = datas.length;
            for (int i = 1; i <= lens; i++) {
                HSSFRow hssfRow = hssfSheet.createRow(i);
                // 第四步,建立單元格,並設置值表頭 設置表頭居中
                HSSFCellStyle style = workbook.createCellStyle();

                //居中樣式
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

                HSSFCell cell = null;
                int len = datas[i-1].length;
                for (int j = 0; j < len; j++) {
                    cell = hssfRow.createCell(j);
                    cell.setCellValue(datas[i-1][j]);
                    cell.setCellStyle((hssfCellStyle));
                }
            }


            // 第七步,將文件輸出到客戶端瀏覽器
            try {
                workbook.write(out);
                out.flush();
                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }


        }catch(Exception e){
            e.printStackTrace();
            throw new Exception("導出信息失敗!");

        }
    }
}
複製代碼

在這個類中有一個導出excel文件的方法,這個方法接受三個參數。apache

第一個參數是表格的標題,是一個字符串類型的一維數組api

第二個參數是表格的數據,存儲了表格中的全部數據數組

第三個參數是servlet的輸出流,用來輸出文件到瀏覽器瀏覽器

具體的poi庫的用法能夠參考這裏bash

3、建立excel輸出控制器

建立一個名爲ExcelController的類, 類中建立一個方法叫excel,接受HttpServletResponse類型的參數。

修改 @RequestMapping註解爲:

@RequestMapping(value = "excel", produces = "application/binary;charset=UTF-8")
複製代碼

指明返回給瀏覽器的數據類型爲二進制文件。

添加上 @ResponseBody註解

完整代碼爲:

package com.learn.controller;

import com.learn.com.learn.tool.ExcelExport;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
public class ExcelController{
    private ExcelExport excelExport = new ExcelExport();

    /** * * @param response * @return */
    @RequestMapping(value = "excel", produces = "application/binary;charset=UTF-8")
    @ResponseBody
    public String excel(HttpServletResponse response) {
        try{
            ServletOutputStream out=response.getOutputStream();
            try {
                //設置文件頭:最後一個參數是設置下載文件名
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(1+".xls", "UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            String[] titles = { "用戶id", "用戶姓名", "用戶密碼", "用戶年齡" };
            String[][] datas = {{"1", "2"}, {"3", "4"}};
            //調用導出excel文件方法
            excelExport.export(titles,datas, out);
            return "success";
        } catch(Exception e){
            e.printStackTrace();
            return "導出信息失敗";
        }

    }

}
複製代碼

運行效果爲:

相關文章
相關標籤/搜索