在Controller层,定义如下
@ApiOperation(value = "条件导出门店表格信息",tags="管理端-活跃门店")
@RequestMapping(value = "/exportStoreTableResult", method = RequestMethod.GET)
public void exportStoresInfo(HttpServletResponse getResponse, @ModelAttribute("StoreGetEntity") StoreGetEntity storeGetEntity) throws IOException, CommonException {
storeActiveService.exportStoreTableByConditions(getResponse,storeGetEntity);
}
在ServiceImpl层,定义如下
/**
* @author weiguyu
* 表格文件导出
*/
@Override
public void exportStoreTableByConditions(HttpServletResponse getResponse, StoreGetEntity storeGetEntity) throws IOException, CommonException {
//新建RetEntity对象,这里怎么查询出来省略,主要是如何写入临时文件
List<Store> stores = storeService.searchForStore(storeGetEntity).getRecords();
//判断查询结果
if(stores!=null){
// 写入临时文件
File tempFile = File.createTempFile("vehicle", ".csv");
CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(), ',', Charset.forName("UTF-8"));
// 写表头
long s = System.currentTimeMillis();
System.err.println();
String[] headers = { "门店", "活跃度", "联系人", "联系电话", "标签", "运营人员", "运营商", "销售人员", "创建时间" };
csvWriter.writeRecord(headers);
for (Store cuo : stores) {
csvWriter.write(cuo.getName());
csvWriter.write(cuo.getSleepDay()+"天未活跃");
csvWriter.write(cuo.getManagerName());
csvWriter.write(cuo.getManagerMobile());
csvWriter.write(cuo.getTag());
csvWriter.write(cuo.getAgentUserName());
csvWriter.write(cuo.getAgentName());
csvWriter.write(cuo.getCcyAdminUserName());
csvWriter.write(cuo.getDateAdded());
csvWriter.endRecord();
}
csvWriter.close();
long e = System.currentTimeMillis();
System.err.println(e - s);
/**
* 写入csv结束,写出流
*/
java.io.OutputStream out = getResponse.getOutputStream();
byte[] b = new byte[10240];
java.io.File fileLoad = new java.io.File(tempFile.getCanonicalPath());
getResponse.reset();
getResponse.setContentType("application/csv");
getResponse.setHeader("content-disposition", "attachment; filename=vehicleModel.csv");
long fileLength = fileLoad.length();
String length1 = String.valueOf(fileLength);
getResponse.setHeader("Content_Length", length1);
java.io.FileInputStream in = new java.io.FileInputStream(fileLoad);
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n); // 每次写入out1024字节
}
in.close();
out.close();
tempFile.delete();
}else{
throw new CommonException(CommonConstant.RESULT_CODE_EXPECTATION_FAILED,"没有找到数据");
}
}
}
前端另存为excel表格就行。