Spring学习手册 2:Spring MVC 导出excel表格

目录

完整代码在这

Spring 导出excel表格有很多种方法,可以直接用设置文件头的方法,也可以使用ContentNegotiatingViewResolver 直接将excel文件直接解析成view。

一、配置文件要加上哪些东西?

首先,如果采用设置响应头的方式来导出excel文件,并不需要配置得很复杂,只要加上一个excel的处理库和Java-servlet库就可以。在这里,我使用了apache-poi库。

完整pom配置文件

<?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>
复制代码

二、依据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文件的方法,这个方法接受三个参数。

第一个参数是表格的标题,是一个字符串类型的一维数组

第二个参数是表格的数据,存储了表格中的所有数据

第三个参数是servlet的输出流,用来输出文件到浏览器

具体的poi库的用法可以参考这里

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

    }

}
复制代码
运行效果为:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值