参考链接 :https://www.yuque.com/easyexcel/doc/easyexcel
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
</dependency>
@Data
public class ProductOutboundDetail implements Serializable {
private static final long serialVersionUID = 1L;
@ExcelProperty("序号")
private Integer num;
@ExcelProperty("品名")
private String productName;
@ExcelProperty("规格")
private String productGrades;
@ExcelProperty("单位")
private String drugUnit;
@ExcelProperty("生产批次")
private String batchNum;
@DateTimeFormat("yyyy-MM-dd")
private Date bestBefore;
@ExcelProperty("单价(元)")
private BigDecimal sellPrice;
@ExcelProperty("数量")
private Integer outboundNum;
@ExcelProperty("金额(元)")
private BigDecimal outmoney;
在web项目的webapp下新建一个文件夹template用来存放excel模版,导出的时候要引入这个模版。
excel模版制定为
id改为num
注意:
<select id="findExcelDataInMasterId" resultType="com.dyt.entity.ProductOutboundDetail">
select product_name,product_grades,drug_unit,outbound_num,sell_price,
outbound_num*sell_price as outmoney,batch_num,best_before
from product_outbound_detail
where master_id = #{master_id}
</select>
第一步:List<ProductOutboundDetail> findExcelDataInMasterId (Integer masterId);
第二步:
/**
* 导出excel数据
*/
@Override
public List<ProductOutboundDetail> findExcelDataInMasterId(Integer masterId) {
List<ProductOutboundDetail> excelDataInMasterId = productOutboundDetailDao.findExcelDataInMasterId(masterId);
return excelDataInMasterId;
}
第三步:
List<ProductOutboundDetail> findExcelDataInMasterId (Integer masterId);
BigDecimalUtil ChineseYuanUtil 在分类常用工具中可以找到
第四步:
@ApiOperation(value = "导出出库数据")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "操作成功,返回成功状态码,保存在data集合元素中"),
@ApiResponse(code = 500, message = "内部错误,信息由msg字段返回")
})
@PostMapping("/EasyExcel")
@ResponseBody
public String printEasyExcelTemplate(HttpServletRequest req, HttpServletResponse resp, Integer masterId,String name) throws Exception {
//1.配置下载属性
resp.setContentType("application/x-msdownload");
resp.setCharacterEncoding("utf-8");
//2.设置文件名
String fileName ="大养堂出库表" + "-" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xlsx";
//3.查询获取数据列表
List<ProductOutboundDetail> list = productOutboundDetailService.findExcelDataInMasterId(masterId);
//为表格添加序号
for(int i=0; i < list.size(); i++){
int n= i+1;
list.get(i).setNum(n);
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("id",masterId);
map.put("isDel",false);
ProductOutboundTable outTable = productOutboundTableService.findProductOutboundTableByxxx(map);
//4.配置对象数据map
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("customerName",outTable.getCustomerName());
map1.put("outboundDate",new SimpleDateFormat("yyyy-MM-dd").format(outTable.getOutboundDate()));
map1.put("outboundMoney", BigDecimalUtil.formatToNumber(new BigDecimal(String.valueOf(outTable.getOutboundMoney()))));
map1.put("outboundMoney1", ChineseYuanUtil.number2CNMontrayUnit(outTable.getOutboundMoney()));
map1.put("name",name);
//5.获取模板路径
HttpSession session = req.getSession();
String path = session.getServletContext().getRealPath("/")+"/template/outbound.xlsx";
//6.获取ExcelWrite对象
ExcelWriter writer = EasyExcel.write(fileName)
.head(ProductOutboundDetail.class) //指定头
.withTemplate(path) //加载模板
.build(); //构造write对象
//7.获取WriterSheet对象
WriteSheet sheet = EasyExcel.writerSheet().build();
//8.填充列表,自动的创建数据行
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
writer.fill(list, fillConfig, sheet);
//9.填充对象数据
writer.fill(map1,sheet);
//10.释放资源,完成数据下载
writer.finish();
return "success";
}
ExcelUtil工具
package com.dyt.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class ExcelUtil {
public static <T> void writeExcel(HttpServletRequest req, HttpServletResponse resp, String name,String path,
List<T> list,Map<String, Object> map,Class model)throws Exception{
//1.配置下载属性
resp.setContentType("application/x-msdownload");
resp.setCharacterEncoding("utf-8");
//2.设置文件名
String fileName = name + "-" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xlsx";
//3.获取ExcelWrite对象
ExcelWriter writer = EasyExcel.write(fileName)
.head(model) //指定头
.withTemplate(path) //加载模板
.build(); //构造write对象
//4.获取WriterSheet对象
WriteSheet sheet = EasyExcel.writerSheet().build();
//5.填充列表,自动的创建数据行
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
writer.fill(list, fillConfig, sheet);
//6.填充对象数据
writer.fill(map,sheet);
//7.释放资源,完成数据下载
writer.finish();
}
}
Controller层
@ApiOperation(value = "导出出库数据")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "操作成功,返回成功状态码,保存在data集合元素中"),
@ApiResponse(code = 500, message = "内部错误,信息由msg字段返回")
})
@PostMapping("/EasyExcel")
@ResponseBody
public String printEasyExcelTemplate(HttpServletRequest req, HttpServletResponse resp, Integer masterId,String name) throws Exception {
//1.设置表名称
String fileName ="大养堂出库表";
HttpSession session = req.getSession();
//2.获取模版地址
String path = session.getServletContext().getRealPath("/")+"/template/outbound.xlsx";
//3.查询获取数据列表 方法
List<ProductOutboundDetail> list = productOutboundDetailService.findExcelDataInMasterId(masterId);
//为表格添加序号
for(int i=0; i < list.size(); i++){
int n= i+1;
list.get(i).setNum(n);
}
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("id",masterId);
map2.put("isDel",false);
// 方法
ProductOutboundTable outTable = productOutboundTableService.findProductOutboundTableByxxx(map2);
//4.配置对象数据map
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("customerName",outTable.getCustomerName());
map3.put("outboundDate",new SimpleDateFormat("yyyy-MM-dd").format(outTable.getOutboundDate()));
map3.put("outboundMoney", BigDecimalUtil.formatToNumber(new BigDecimal(String.valueOf(outTable.getOutboundMoney()))));
map3.put("outboundMoney1", ChineseYuanUtil.number2CNMontrayUnit(outTable.getOutboundMoney()));
map3.put("name",name);
ExcelUtil.writeExcel(req,resp,fileName,path,list,map3,ProductOutboundDetail.class);
return "success";
}
public class ExcelUtil extends HttpServlet {
public static <T> void writeExcel(HttpServletRequest req, HttpServletResponse resp, String filePath, String path,
List<T> list, Map<String, Object> map, Class model)throws Exception{
//6.获取ExcelWrite对象
ExcelWriter writer = EasyExcel.write(filePath)
.head(model) //指定头
.withTemplate(path) //加载模板
.build(); //构造write对象
//7.获取WriterSheet对象
WriteSheet sheet = EasyExcel.writerSheet().build();
//8.填充列表,自动的创建数据行
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
writer.fill(list, fillConfig, sheet);
//9.填充对象数据
writer.fill(map,sheet);
//downLoadFile(substring, resp);
//10.释放资源,完成数据下载
writer.finish();
}
}
@ApiOperation(value = "导出出库数据")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "操作成功,返回成功状态码,保存在data集合元素中"),
@ApiResponse(code = 500, message = "内部错误,信息由msg字段返回")
})
@PostMapping(value ="/EasyExcel")
@ResponseBody
public String printEasyExcelTemplate(HttpServletRequest req, HttpServletResponse resp, Integer masterId,String name) throws Exception {
//1.设置表名称
HttpSession session = req.getSession();
String fileName = session.getServletContext().getRealPath("/") + "export" + File.separator
+ "大养堂出库表" + "-"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date())
+ "-" + (int)((Math.random()*9+1)*1000) + ".xlsx" ;
//2.获取模版地址
//session.getServletContext().getRealPath("/");
String path =session.getServletContext().getRealPath("/") + "template" + File.separator + "outbound.xlsx";
//3.查询获取数据列表
List<ProductOutboundDetail> list = productOutboundDetailService.findExcelDataInMasterId(masterId);
//为表格添加序号
for(int i=0; i < list.size(); i++){
int n= i+1;
list.get(i).setNum(n);
}
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("id",masterId);
map2.put("isDel",false);
ProductOutboundTable outTable = productOutboundTableService.findProductOutboundTableByxxx(map2);
//4.配置对象数据map
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("customerName",outTable.getCustomerName());
map3.put("outboundDate",new SimpleDateFormat("yyyy-MM-dd").format(outTable.getOutboundDate()));
map3.put("outboundMoney", BigDecimalUtil.formatToNumber(new BigDecimal(String.valueOf(outTable.getOutboundMoney()))));
map3.put("outboundMoney1", ChineseYuanUtil.number2CNMontrayUnit(outTable.getOutboundMoney()));
map3.put("name",name);
ExcelUtil.writeExcel(req,resp,fileName,path,list,map3,ProductOutboundDetail.class);
return URLEncoder.encode(fileName, "UTF-8");
}
fileName 返回下载链接让前端使用
导出
//查询导出文件url,执行导出程序
btnExportExcel() {
var data = Qs.stringify({
//根据自己需求设置参数
masterId: this.masterId,
name: this.user.name,
})
axios
.post(
//后台提供的接口
this.GLOBAL.BASE_URL +
"KFGL0601-web/productPutInStorageDetail/EasyExcel",
data
)
.then(res => {
//url解码 修整正确下载url
this.fileName = decodeURIComponent(res.data).replace('+', ' ').substring(51)
//导出
this.downloadExcel();
})
.catch(err => {
console.log(err);
});
},
//导出Excel
downloadExcel() {
var elemIF = document.createElement('iframe')
elemIF.src = this.GLOBAL.BASE_URL + this.fileName
elemIF.style.display = 'none'
document.body.appendChild(elemIF)
},