话不多说,直接上代码
数据库表如下
代码结构如下
controller
package com.yuanyuan.smp.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yuanyuan.smp.entity.User;
import com.yuanyuan.smp.service.IUserService;
import com.yuanyuan.smp.utils.FileUtil;
@RestController
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("/")
public String hello() {
return "hello";
}
@RequestMapping("/exportExcel")
public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
List<User> userList = userService.selectAll();
// 创建工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建表
HSSFSheet sheet = workbook.createSheet("用户信息");
// 创建行
HSSFRow row = sheet.createRow(0);
// 创建单元格样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
// 表头
String[] head = {"姓名", "年龄"};
HSSFCell cell;
// 设置表头
for(int iHead=0; iHead<head.length; iHead++) {
cell = row.createCell(iHead);
cell.setCellValue(head[iHead]);
cell.setCellStyle(cellStyle);
}
// 设置表格内容
for(int iBody=0; iBody<userList.size(); iBody++) {
row = sheet.createRow(iBody+1);
User u = userList.get(iBody);
String[] userArray = new String[2];
userArray[0]=u.getName();
userArray[1]=u.getAge() + "";
for(int iArray=0; iArray<userArray.length; iArray++) {
row.createCell(iArray).setCellValue(userArray[iArray]);
}
}
// 生成Excel文件
FileUtil.createFile(response, workbook);
}
}
实体类
package com.yuanyuan.smp.entity;
import java.io.Serializable;
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2895782870082326368L;
private Integer userId;
private String name;
private Integer age;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
mapper
package com.yuanyuan.smp.mapper;
import java.util.List;
import com.yuanyuan.smp.entity.User;
public interface UserMapper {
List<User> selectAll();
}
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.yuanyuan.smp.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.yuanyuan.smp.entity.User" >
<id column="user_id" property="userId" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
user_id, name, age
</sql>
<select id="selectAll" resultMap="BaseResultMap" >
select
<include refid="Base_Column_List" />
from user
</select>
</mapper>
Service
package com.yuanyuan.smp.service;
import java.util.List;
import com.yuanyuan.smp.entity.User;
public interface IUserService {
List<User> selectAll();
}
package com.yuanyuan.smp.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yuanyuan.smp.entity.User;
import com.yuanyuan.smp.mapper.UserMapper;
@Service
public class UserService implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> selectAll() {
return userMapper.selectAll();
}
}
utils
package com.yuanyuan.smp.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class FileUtil {
public static void createFile(HttpServletResponse response, HSSFWorkbook workbook) {
// 设置文件名
String fileName ="用户信息";
try {
// 捕获内存缓冲区的数据,转换成字节数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
workbook.write(out);
// 获取内存缓冲中的数据
byte[] content = out.toByteArray();
// 将字节数组转化为输入流
InputStream in = new ByteArrayInputStream(content);
//通过调用reset()方法可以重新定位。
response.reset();
// 如果文件名是英文名不需要加编码格式,如果是中文名需要添加"iso-8859-1"防止乱码
response.setHeader("Content-Disposition", "attachment; filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
response.addHeader("Content-Length", "" + content.length);
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
ServletOutputStream outputStream = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(in);
BufferedOutputStream bos = new BufferedOutputStream(outputStream);
byte[] buff = new byte[8192];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
启动类
package com.yuanyuan.smp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages= {"com.yuanyuan.smp.mapper"})
public class SmpApplication {
public static void main(String[] args) {
SpringApplication.run(SmpApplication.class, args);
}
}
application.yml
server:
port: 8088
context-path: /
tomcat:
uri-encoding: UTF-8
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
username: root
password: root
mybatis:
mapper-locations: com.yuanyuan.smp.mapper/*.xml
pom.xml
<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.yuanyuan.smp</groupId>
<artifactId>springboot-mybaits-poi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- spring boot jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- spring boot web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
运行main方法,访问接口http://localhost:8088/exportExcel,结果如下