前台vue内容
//下载
handleDownload(){
this.$axios.get('sale/excel')
const res = axios.request({
url: 'sale/excel',
method: 'get', // 以get请求为例
responseType: 'blob'//axios底层对返回数据以流的方式处理
}).then(res=>{
const data = res;
let url = window.URL.createObjectURL(data)
var a = document.createElement('a')
document.body.appendChild(a)
a.href = url;
a.download = '销售表.xlsx'
a.click()
window.URL.revokeObjectURL(url)
})
}
handler层内容
//@RestController
//@RequestMapping("sale") handler层注解
@GetMapping("excel")
public StatusBean excelOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
String[] fields = new String[]{"imei", "orderId", "phone", "price", "status", "discount"};
String[] headers = new String[]{"串码", "订单编号", "联系电话", "商品价格", "订单状态", "折扣"};
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("销售单.xlsx", "UTF-8"));
List<Map> maps = sos.selectExcel();
ServletOutputStream out = response.getOutputStream();
WriteExcel.writeExcel(maps, fields, headers, out);
return StatusBean.getStatusBean(StatusEnum.SUCCESS);
}
service层
@Override
public List<Map> selectExcel() {
List result = new ArrayList();
List<SaleOrderDetail> detail = sodm.selectAllOrderDetail(null);
for (int i = 0; i < detail.size(); i++) {
Map map = new HashMap();
SaleOrderDetail a = detail.get(i);
Integer orderId = a.getOrderId();
SaleOrder saleOrder = new SaleOrder();
saleOrder.setOrderId(orderId);
List<SaleOrder> list = som.selectAllSaleOrder(saleOrder);
map.put("imei", a.getImei());
map.put("orderId", a.getOrderId());
if (list.size() != 0)
map.put("phone", list.get(0).getPhone());
else map.put("phone", null);
map.put("price", a.getPrice());
map.put("status", a.getStatus());
map.put("discount", a.getDiscount());
result.add(map);
}
return result;
}
excel下载方法
public class WriteExcel {
public static void writeExcel(List<Map> maps,String[] fields,String[] headers, OutputStream out) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();//向workbook对象中放数据
XSSFSheet sheet = workbook.createSheet("销售出库单");
XSSFRow row1 = sheet.createRow(0);
for(int j=0;j<headers.length;j++){
XSSFCell cell = row1.createCell(j);
cell.setCellValue(headers[j]);
}
for (int i=0;i<maps.size();i++) {
Map map = maps.get(i);//{usalary=22222.21, uname=战三1, uphone=123123123, uage=11, udate=2020-11-14},map是无序的
XSSFRow row = sheet.createRow(i+1);
for(int j=0;j<fields.length;j++){
XSSFCell cell = row.createCell(j);
String colName = fields[j];
Object value = map.get(colName);
cell.setCellValue(String.valueOf(value));
}
}
workbook.write(out);
out.close();
}
}