记一段完整的代码
// Controller 层
/**
* 导出CSV文件
* @param
* @return
*/
@ApiOperation(value = "导出CSV文件")
@PostMapping("/uploadUnitFile")
@Log("导出CSV文件")
public void uploadUnitFile(HttpServletResponse response,
@RequestBody UnitVo unitVo){
unitService.uploadUnitFile(response, unitVo);
}
// 接口
/**
* 单位导出
* @param response
* @param unitVo
*/
void uploadUnitFile(HttpServletResponse response, UnitVo unitVo);
// 实现方法
/**
* 单位导出
* @param response
* @param unitVo
*/
@Override
public void uploadUnitFile(HttpServletResponse response, UnitVo unitVo) {
unitVo.setPage(1);
// 查询数据库中总共有多少条数据
Integer count = unitMapper.selectCountNumber();
unitVo.setPageSize(count);
ListVo listVo = getDefectItemList(unitVo);
List<Unit> unitList = listVo.getList();
List resultList = new ArrayList();
CSVPrinter printer = null;
try {
//格式化时间
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
Object[] objects = null;
for (Unit unit : unitList) {
ArrayList<Object> arrayList = new ArrayList<>();
String factoryName = factoryMapper.selectNameById(unit.getFactoryId());
arrayList.add(factoryName);
arrayList.add(unit.getName());
arrayList.add(unit.getCode());
arrayList.add(unit.getRemarks() == null ? "" : unit.getRemarks());
arrayList.add(unit.getCreateTime());
arrayList.add(unit.getUpdateTime());
Integer status = unit.getStatus();
String statusName=null;
if(status.equals(0)){
statusName = "删除";
}
if(status.equals(1)){
statusName = "正常";
}
if(status.equals(2)){
statusName = "停用";
}
arrayList.add(statusName);
resultList.add(arrayList);
}
String path = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
File folder = new File(resourcePath, path);
if(!folder.isDirectory()) folder.mkdirs();
//截取文件扩展名
//创建随机的文件名
String name = UUID.randomUUID().toString() + ".csv";
File file = new File(folder, name);
BufferedWriter fw = new BufferedWriter (new OutputStreamWriter(
new FileOutputStream(file.getAbsoluteFile(),true),"gbk"));
printer = CSVFormat.EXCEL.print(fw);
Object[] cells = {"工厂名称", "单位名称","编号","备注","创建时间","更新时间","备注"};
printer.printRecord(cells);
for (int i = 0; i < resultList.size(); i++) {
List o = (List) resultList.get(i);
objects = o.toArray();
printer.printRecord(objects);
System.out.println(objects);
}
printer.flush();
printer.close();
File file1 = new File(resourcePath+'/'+path+'/'+name);
FileInputStream fileInputStream = new FileInputStream(file1);
response.setCharacterEncoding("GBK");
response.setHeader("Content-Type", "application/csv");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
OutputStream out = response.getOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
out.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public ListVo getDefectItemList(UnitVo unitVo) {
QueryWrapper<Unit> queryWrapper = new QueryWrapper<>();
FactoryUser user = SecurityUtil.getFactoryUser();
queryWrapper.ne("status",0)
.eq("factory_id",user.getFactoryId());
if (unitVo.getName() != null){
queryWrapper.like("name",unitVo.getName());
}
Page<Unit> page = new Page<>(unitVo.getPage(),unitVo.getPageSize());
unitMapper.selectPage(page,queryWrapper);
ListVo listVo = new ListVo();
listVo.setList(page.getRecords());
listVo.setPage(unitVo.getPage());
listVo.setTotalPages(page.getPages());
listVo.setTotalCount(page.getTotal());
listVo.setPageSize(unitVo.getPageSize());
return listVo;
}