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 "导出信息失败";
        }

    }

}
复制代码

运行效果为:

相关文章
相关标签/搜索