源码下载
添加依赖 pom.xml
org.apache.poi
poi
3.13
org.apache.poi
poi-ooxml
3.13
com.baomidou
mybatis-plus-boot-starter
3.1 .1
com.sdsvs.finsvc
mysql-connector
1.1
org.projectlombok
lombok
true
配置文件配置 application.yml
#端口号
server:
port: 8080
##数据库的配置信息
spring:
datasource:
url: jdbc:mysql: // localhost:3306/user?serverTimezone=UTC&?useUnicode=true&characterEncoding=utf8 #自己的 数据库 名称
username: root
password: root
driver -class -name: com.mysql.jdbc.Driver
mybatis:
#开启驼峰命名法
configuration:
map -underscore-to-camel-case : true
mybatis -plus:
# xml地址
mapper -locations: classpath:mapper/* Mapper.xml
# 实体扫描,多个package用逗号或者分号分隔
type-aliases-package: com.niuben.entity #自己的实体类地址
configuration:
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Excel工具类 ExcelUtils
package com.niuben.utils;
import com.niuben.model.ExcelData;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel. *;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide;
import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
/* *
* @author: NiuBen
* @date: Created in 2019/12/15 19:48
* @description:
*/
public class ExcelUtils {
/* *
* 使用浏览器选择路径下载
* @param response
* @param fileName
* @param data
* @throws Exception
*/
public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception {
// 告诉浏览器用什么软件可以打开此文件
response.setHeader(" content-Type " , " application/vnd.ms-excel " );
// 下载文件的默认名称
response.setHeader(" Content-Disposition " , " attachment;filename= " + URLEncoder.encode(fileName + " .xlsx " , " utf-8 " ));
exportExcel(data, response.getOutputStream());
}
private static int exportExcel(ExcelData data, OutputStream out ) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
int rowIndex = 0 ;
try {
String sheetName = data.getName();
if (null == sheetName) {
sheetName = " Sheet1 " ;
}
XSSFSheet sheet = wb.createSheet(sheetName);
rowIndex = writeExcel(wb, sheet, data);
wb.write( out );
} catch (Exception e) {
e.printStackTrace();
} finally {
// 此处需要关闭 wb 变量
out .close();
}
return rowIndex;
}
/* *
* 表显示字段
* @param wb
* @param sheet
* @param data
* @return
*/
private static int writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {
int rowIndex = 0 ;
rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
rowIndex = writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
autoSizeColumns(sheet, data.getTitles().size() + 1 );
return rowIndex;
}
/* *
* 设置表头
*
* @param wb
* @param sheet
* @param titles
* @return
*/
private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List titles) {
int rowIndex = 0 ;
int colIndex = 0 ;
Font titleFont = wb.createFont();
// 设置字体
titleFont.setFontName(" simsun " );
// 设置粗体
titleFont.setBoldweight(Short.MAX_VALUE);
// 设置字号
titleFont.setFontHeightInPoints((short ) 14 );
// 设置颜色
titleFont.setColor(IndexedColors.BLACK.index);
XSSFCellStyle titleStyle = wb.createCellStyle();
// 水平居中
titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 垂直居中
titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
// 设置图案颜色
titleStyle.setFillForegroundColor(new XSSFColor(new Color(182 , 184 , 192 )));
// 设置图案样式
titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
titleStyle.setFont(titleFont);
setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0 , 0 , 0 )));
Row titleRow = sheet.createRow(rowIndex);
titleRow.setHeightInPoints( 25 );
colIndex = 0 ;
for (String field : titles) {
Cell cell = titleRow.createCell(colIndex);
cell.setCellValue(field);
cell.setCellStyle(titleStyle);
colIndex ++;
}
rowIndex ++;
return rowIndex;
}
/* *
* 设置内容
*
* @param wb
* @param sheet
* @param rows
* @param rowIndex
* @return
*/
private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List> rows, int rowIndex) {
int colIndex;
Font dataFont = wb.createFont();
dataFont.setFontName( " simsun " );
dataFont.setFontHeightInPoints(( short ) 14 );
dataFont.setColor(IndexedColors.BLACK.index);
XSSFCellStyle dataStyle = wb.createCellStyle();
dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
dataStyle.setFont(dataFont);
setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0 , 0 , 0 )));
for (List rowData : rows) {
Row dataRow = sheet.createRow(rowIndex);
dataRow.setHeightInPoints( 25 );
colIndex = 0 ;
for (Object cellData : rowData) {
Cell cell = dataRow.createCell(colIndex);
if (cellData != null ) {
cell.setCellValue(cellData.toString());
} else {
cell.setCellValue( "" );
}
cell.setCellStyle(dataStyle);
colIndex ++;
}
rowIndex ++;
}
return rowIndex;
}
/* *
* 自动调整列宽
*
* @param sheet
* @param columnNumber
*/
private static void autoSizeColumns(Sheet sheet, int columnNumber) {
for (int i = 0 ; i < columnNumber; i++) {
int orgWidth = sheet.getColumnWidth(i);
sheet.autoSizeColumn(i, true );
int newWidth = (int ) (sheet.getColumnWidth(i) + 100 );
if (newWidth > orgWidth) {
sheet.setColumnWidth(i, newWidth);
} else {
sheet.setColumnWidth(i, orgWidth);
}
}
}
/* *
* 设置边框
*
* @param style
* @param border
* @param color
*/
private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
style.setBorderTop(border);
style.setBorderLeft(border);
style.setBorderRight(border);
style.setBorderBottom(border);
style.setBorderColor(BorderSide.TOP, color);
style.setBorderColor(BorderSide.LEFT, color);
style.setBorderColor(BorderSide.RIGHT, color);
style.setBorderColor(BorderSide.BOTTOM, color);
}
}
创建实体类 UserInfo
package com.niuben.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/* *
* @author: NiuBen
* @date: Created in 2019/12/15 19:59
* @description:
*/
@Data
@EqualsAndHashCode(callSuper = false )
@Accessors(chain = true )
@TableName(value = " userInfo " )
public class UserInfo {
@TableId(value = " ID " , type = IdType.AUTO)
private Integer id;
@TableField( " userName " )
private String userName;
@TableField( " password " )
private String password;
}
创建mapper层 UserInfoMapper
package com.niuben.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.niuben.entity.UserInfo;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserInfoMapper extends BaseMapper {
}
在rescurces下创建 mapper/UserInfoMapper.xml
"1.0 " encoding=" UTF-8 " ?>
"-//mybatis.org//DTD Mapper 3.0//EN " " http://mybatis.org/dtd/mybatis-3-mapper.dtd " >
namespace=" com.niuben.mapper.UserInfo " >
创建service层 UserInfoService
package com.niuben.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.niuben.entity.UserInfo;
public interface UserInfoService extends IService {
}
创建Impl层 UserInfoServiceImpl
package com.niuben.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.niuben.entity.UserInfo;
import com.niuben.mapper.UserInfoMapper;
import com.niuben.service.UserInfoService;
import org.springframework.stereotype.Service;
/* *
* @author: NiuBen
* @date: Created in 2019/12/15 20:05
* @description:
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl implements UserInfoService {
}
创建表格model封装表格数据 ExcelData
package com.niuben.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
/* *
* @author: NiuBen
* @date: Created in 2019/12/15 19:47
* @description:
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExcelData implements Serializable {
private static final long serialVersionUID = 6133772627258154184L ;
/* *
* 表头
*/
private List titles;
/* *
* 数据
*/
private List> rows;
/* *
* 页签名称
*/
private String name;
}
创建controller层 ExcelController
package com.niuben.controller;
import com.niuben.entity.UserInfo;
import com.niuben.model.ExcelData;
import com.niuben.service.impl.UserInfoServiceImpl;
import com.niuben.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/* *
* @author: NiuBen
* @date: Created in 2019/12/15 19:51
* @description:
*/
@Controller
@RequestMapping( " /excel " )
public class ExcelController {
@Autowired
UserInfoServiceImpl userInfoService;
@RequestMapping( " /exportExcel " )
public void test2(HttpServletResponse response){
List list = userInfoService.list();
ExcelData data = new ExcelData();
// 设置sheet页名
data.setName(" hello " );
List titles = new ArrayList();
titles.add( " ID " );
titles.add( " 用户名 " );
titles.add( " 密码 " );
data.setTitles(titles);
List > rows = new ArrayList();
for (int i = 0 , length = list.size();i){
UserInfo userInfo = list.get (i);
List row = new ArrayList();
row.add(userInfo.getId());
row.add(userInfo.getUserName());
row.add(userInfo.getPassword());
rows.add(row);
}
data.setRows(rows);
try {
ExcelUtils.exportExcel(response, " 表格名称 " ,data);
} catch (Exception e){
e.printStackTrace();
}
}
}