pom文件导入依赖:
<properties>
<poi.version>3.17</poi.version>
</properties>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.version}</version>
</dependency>
模板:
controller:
package com.zu.zs.controller;
import com.alibaba.fastjson.JSONObject;
import com.zu.zs.service.OrderService;
import com.zu.zs.utils.TemplateExcelUtil;
import com.zy.pojo.*;
import com.zy.zs.common.ResultUtil;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
public class OrderController {
@Resource
private OrderService orderService;
//poi:把数据库数据导出到excel表格
@RequestMapping("/poiFile/{orderStatus}")
//我是根据session里的用户名和订单状态进行的sql语句查询
public boolean poiFile(HttpSession session,@PathVariable("orderStatus") Integer orderStatus){
User user = (User) session.getAttribute("user");
//因为我的excel表格里用到了时间,所以在这对当前时间进行了转换
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
//把当前时间转成sdf1形式的字符串
String format = sdf1.format(new Date());
//这是要导出到excel表格里的地址,我的命名方式用了时间戳的形式(orderCode_5698740745687.xlsx)
String target = "D:\\ChouChou\\xlsx_directory"
+ File.separator+"orderCode"+"_"+System.currentTimeMillis()+".xlsx";
//模板名称
String temp = "orderCode_2019080711112.xlsx";
String realPath = session.getServletContext().getRealPath("/jsps/temp");
//最终模板地址
temp=realPath+File.separator+temp;
//参数列表,模板里有几个参数需要定义,就写几个参数
String[] params = new String[2];
//params[0]=user.getName();
params[0]="陈红";
params[1]=format;
//根据需求查询订单
// List<Order> list = orderService.findAllOrder(orderStatus,user.getName());
List<Order> list = orderService.findAllOrder(orderStatus,"wzy");
//Excel表对应的JavaBean属性的集合
List<String> list1 = propertyList();
//new一个工具类对象
TemplateExcelUtil excelUtil = new TemplateExcelUtil();
//调用工具类中的导出方法,并传入参数
excelUtil.exportExcel(temp,target,params,list1,list);
return true;
}
private List<String> propertyList(){
List<String> propertyList = new ArrayList<>();
propertyList.add("id");
propertyList.add("orderNumber");
propertyList.add("userName");
propertyList.add("orderPrice");
propertyList.add("orderStatus");
propertyList.add("createOrderTime");
propertyList.add("paymentType");
propertyList.add("userId");
propertyList.add("trackingNumber");
propertyList.add("addressId");
return propertyList;
}
}
工具类 TemplateExcelUtil:
package com.zu.zs.utils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class TemplateExcelUtil<T> {
/**
* 导出excel
* 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出
* temp 模板路径
* target 存储目标地址
* params 表头里的参数数组
* headersId 表格属性列名对应的javaBean字段---你需要导出的字段名(为了更灵活控制你想要导出的字段)
* dtoList 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象
* 返回响应体
*/
public void exportExcel(String temp,String target, String[] params,List<String> headersId,
List<T> dtoList) {
/*(二)字段*/
Map<Integer, String> titleFieldMap = new HashMap<>();
int value = 0;
for (int i = 0; i < headersId.size(); i++) {
if (!headersId.get(i).equals(null)) {
titleFieldMap.put(value, headersId.get(i));
value++;
}
}
/* (三)读取模板*/
XSSFWorkbook wb = null;
File file = new File(temp);
try {
wb = (XSSFWorkbook) WorkbookFactory.create(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/** 得到第一个sheet */
XSSFSheet sheet = wb.getSheetAt(0);
sheet.setDefaultColumnWidth((short)20);
//补充标题头的参数
//1和0分别表示第几行第几列,如果有多个参数就多复制几份这个用
XSSFRow row0 = sheet.getRow(1);
XSSFCell cell00 = row0.getCell(0);
String string00 = MessageFormat.format(cell00.getStringCellValue(),params);
cell00.setCellValue(string00);
/*XSSFRow row0 = sheet.getRow(2);
XSSFCell cell00 = row0.getCell(0);
String string00 = MessageFormat.format(cell00.getStringCellValue(),params);
cell00.setCellValue(string00);*/
//得到表格的样式
//因为我的模板里定义的就3行,我就让它读取我三行样式,定义几行就写几
XSSFCellStyle cellStyle = sheet.getRow(3).getCell(0).getCellStyle();
XSSFRow row=null;
XSSFCell cell=null;
//表格标题一行的字段的集合
Collection zdC = titleFieldMap.values();
Iterator<T> labIt = dtoList.iterator();//总记录的迭代器
//这个序列号,是你在下标为几的下面开始输入数据,就写几
int zdRow =2;//列序号
while (labIt.hasNext()) {//记录的迭代器,遍历总记录
int zdCell = 0;
zdRow++;
row = sheet.createRow(zdRow);
T l = (T) labIt.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = l.getClass().getDeclaredFields();//获得JavaBean全部属性
for (short i = 0; i < fields.length; i++) {//遍历属性,比对
Field field = fields[i];
String fieldName = field.getName();//属性名
Iterator<String> zdIt = zdC.iterator();//一条字段的集合的迭代器
while (zdIt.hasNext()) {//遍历要导出的字段集合
if (zdIt.next().equals(fieldName)) {//比对JavaBean的属性名,一致就写入,不一致就丢弃
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);//拿到属性的get方法
Class tCls = l.getClass();//拿到JavaBean对象
try {
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});//通过JavaBean对象拿到该属性的get方法,从而进行操控
Object val = getMethod.invoke(l, new Object[] {});//操控该对象属性的get方法,从而拿到属性值
Class t = getMethod.getReturnType();
cell = row.createCell((short) zdCell);
cell.setCellStyle(cellStyle);//单元格样式
//根据值的类型设置单元格的值
switch (t.getName()) {
case "java.lang.Integer":
if(null!=val){
cell.setCellValue((Integer)val);
}
break;
case "java.util.Date":
if(null!=val){
Date date=(Date)val;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
cell.setCellValue(sdf.format(date));
}
break;
default:
cell.setCellValue(String.valueOf(val));
break;
}
zdCell++;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
//4.存储文件
try {
FileOutputStream out=new FileOutputStream(target);
wb.write(out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Excel读取 操作
*/
public static List<List<String>> readExcel(InputStream is)
throws IOException {
Workbook wb = null;
try {
wb = WorkbookFactory.create(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/** 得到第一个sheet */
Sheet sheet = wb.getSheetAt(0);
/** 得到Excel的行数 */
int totalRows = sheet.getPhysicalNumberOfRows();
/** 得到Excel的列数 */
int totalCells = 0;
if (totalRows >= 1 && sheet.getRow(0) != null) {
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<List<String>> dataLst = new ArrayList<List<String>>();
/** 循环Excel的行 */
for (int r = 0; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null)
continue;
List<String> rowLst = new ArrayList<String>();
/** 循环Excel的列 */
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
/*HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
cellValue= hSSFDataFormatter.formatCellValue(cell);*/
// 以下是判断数据的类型
CellType type = cell.getCellTypeEnum();
switch (type) {
case NUMERIC: // 数字
cellValue = cell.getNumericCellValue() + "";
break;
case STRING: // 字符串
cellValue = cell.getStringCellValue();
break;
case BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break;
case BLANK: // 空值
cellValue = "";
break;
case _NONE: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
}
rowLst.add(cellValue);
}
/** 保存第r行的第c列 */
dataLst.add(rowLst);
}
return dataLst;
}
}
serviceImpl、mapper:
serviceimpl:
//导出订单
@Override
public List<Order> findAllOrder(Integer orderStatus,String userName) {
return orderMapper.findAllOrder(orderStatus,userName);
}
mapper:
//poi导出数据到excel
List<Order> findAllOrder(@Param("orderStatus") Integer orderStatus, @Param("userName") String userName);
mapper.xml:
<!--查询当前状态的订单集合-->
<select id="findAllOrder" resultType="com.zy.pojo.Order">
select id, order_number, user_name,
order_price,order_status, create_order_time,payment_type,user_id,tracking_number,address_id
from `order`
where order_status=#{orderStatus}
and user_name=#{userName};
</select>