修复导出相关问题

hyx_2024-10-12_xgfPerson
shanao 2024-09-10 14:10:42 +08:00
parent c6ea9844ca
commit dceba5c4b2
6 changed files with 121 additions and 118 deletions

View File

@ -9,19 +9,21 @@ import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.accident.AccidentRecords;
import com.zcloud.service.accident.AccidentRecordsService;
import com.zcloud.util.ObjectExcelView;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;
@RestController
@Controller
@RequiredArgsConstructor
@RequestMapping("/accident")
public class AccidentRecordsController extends BaseController {
@ -35,6 +37,7 @@ public class AccidentRecordsController extends BaseController {
* @param request
* @return
*/
@ResponseBody
@RequestMapping(value = "/page")
public Map<String, Object> queryPage(Page page, HttpServletRequest request) {
page.setPd(new PageData(request));
@ -51,6 +54,7 @@ public class AccidentRecordsController extends BaseController {
* @param id id
* @return
*/
@ResponseBody
@RequestMapping("/{id}")
public Map<String, Object> getById(@PathVariable("id") Long id) {
Map<String, Object> result = new HashMap<>();
@ -65,6 +69,7 @@ public class AccidentRecordsController extends BaseController {
* @param request
* @return
*/
@ResponseBody
@RequestMapping("/save")
public Map<String, Object> save(HttpServletRequest request) {
AccidentRecords accidentRecords = BeanUtil.mapToBean(new PageData(request), AccidentRecords.class, true);
@ -80,6 +85,7 @@ public class AccidentRecordsController extends BaseController {
* @param request
* @return
*/
@ResponseBody
@RequestMapping("/update")
public Map<String, Object> update(HttpServletRequest request) {
AccidentRecords accidentRecords = BeanUtil.mapToBean(new PageData(request), AccidentRecords.class, true);
@ -96,6 +102,7 @@ public class AccidentRecordsController extends BaseController {
* @param values id
* @return
*/
@ResponseBody
@RequestMapping("/delete/{ids}")
public Map<String, Object> delete(@PathVariable("ids") String values) {
if (StrUtil.isEmpty(values)) {
@ -113,25 +120,26 @@ public class AccidentRecordsController extends BaseController {
* excel
*
* @param request
* @param response
* @return
*/
@RequestMapping("/export/excel")
public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
accidentRecordsService.exportExcel(new PageData(request), response);
public ModelAndView exportExcel(HttpServletRequest request) {
Map<String, Object> dataMap = accidentRecordsService.exportExcel(new PageData(request));
return new ModelAndView(new ObjectExcelView(), dataMap);
}
/**
* excel
*
* @param file
*/
@RequestMapping("/import/excel")
public void importExcel(@RequestParam("file") MultipartFile file) {
if (file == null || file.isEmpty()) {
throw new RuntimeException("文件不能为空");
}
accidentRecordsService.importExcel(file);
}
// /**
// * 导入excel
// *
// * @param file 文件
// */
// @RequestMapping("/import/excel")
// public void importExcel(@RequestParam("file") MultipartFile file) {
// if (file == null || file.isEmpty()) {
// throw new RuntimeException("文件不能为空");
// }
// accidentRecordsService.importExcel(file);
// }
/**
*
@ -139,6 +147,7 @@ public class AccidentRecordsController extends BaseController {
* @param file
* @return
*/
@ResponseBody
@RequestMapping("/import/photos")
public Map<String, Object> importPhotos(@RequestParam("file") MultipartFile file) {
if (file == null || file.isEmpty()) {
@ -156,6 +165,7 @@ public class AccidentRecordsController extends BaseController {
* @param request
* @return
*/
@ResponseBody
@RequestMapping("/delete/photos")
public Map<String, Object> deletePhotos(HttpServletRequest request) {
String path = new PageData(request).getString("path");

View File

@ -57,5 +57,5 @@ public interface AccidentRecordsMapper {
* @param pd
* @return
*/
List<AccidentRecordsExcel> listExcel(PageData pd);
List<AccidentRecordsExcel> listExcel(@Param("pd") PageData pd);
}

View File

@ -5,8 +5,8 @@ import com.zcloud.entity.PageData;
import com.zcloud.entity.accident.AccidentRecords;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
public interface AccidentRecordsService {
@ -51,16 +51,16 @@ public interface AccidentRecordsService {
* Excel
*
* @param pd
* @param response
* @return
*/
void exportExcel(PageData pd, HttpServletResponse response);
Map<String,Object> exportExcel(PageData pd);
/**
* Excel
*
* @param file
*/
void importExcel(MultipartFile file);
// /**
// * 导入Excel
// *
// * @param file 文件
// */
// void importExcel(MultipartFile file);
/**
*

View File

@ -1,12 +1,9 @@
package com.zcloud.service.accident.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.*;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.accident.AccidentRecords;
@ -15,27 +12,18 @@ import com.zcloud.entity.accident.dto.AccidentRecordsExcel;
import com.zcloud.mapper.datasource.accident.AccidentRecordsMapper;
import com.zcloud.service.accident.AccidentRecordsService;
import com.zcloud.service.bus.ImgFilesService;
import com.zcloud.service.system.DictionariesService;
import com.zcloud.util.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@ -44,15 +32,15 @@ import java.util.stream.Collectors;
public class AccidentRecordsServiceImpl implements AccidentRecordsService {
private final AccidentRecordsMapper accidentRecordsMapper;
private final SqlSessionFactory sqlSessionFactory;
private final DictionariesService dictionariesService;
private static final Map<String, String> HEADER_ALIAS_CACHE;
//private final SqlSessionFactory sqlSessionFactory;
//private final DictionariesService dictionariesService;
private static final List<Field> HEADER_ALIAS_CACHE;
private final ImgFilesService imgFilesService;
static {
HEADER_ALIAS_CACHE = Arrays.stream(ReflectUtil.getFields(AccidentRecordsExcel.class))
.filter(field -> field.isAnnotationPresent(ExcelValue.class))
.collect(Collectors.toMap(Field::getName, field -> field.getAnnotation(ExcelValue.class).value()));
.collect(Collectors.toList());
}
@Override
@ -98,70 +86,71 @@ public class AccidentRecordsServiceImpl implements AccidentRecordsService {
}
@Override
public void exportExcel(PageData pd, HttpServletResponse response) {
public Map<String, Object> exportExcel(PageData pd) {
// 查询数据
pd.put("corpInfoId", Jurisdiction.getCORPINFO_ID());
List<AccidentRecordsExcel> list = accidentRecordsMapper.listExcel(pd);
List<AccidentRecordsExcel> excels = accidentRecordsMapper.listExcel(pd);
// 检查查询结果是否为空
if (list == null || list.isEmpty()) {
if (excels == null || excels.isEmpty()) {
throw new RuntimeException("没有查询到数据");
}
Map<String, Object> dataMap = new HashMap<String, Object>() {{
put("filename", "事故调查");
put("titles", HEADER_ALIAS_CACHE.stream().map(field -> field.getAnnotation(ExcelValue.class)
.value()).collect(Collectors.toList()));
}};
// 设置响应头
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + URLUtil.encode("事故调查表", CharsetUtil.UTF_8) + ".xlsx");
try (ExcelWriter writer = ExcelUtil.getBigWriter()) {
writer.setHeaderAlias(HEADER_ALIAS_CACHE)
.setOnlyAlias(true)
.write(list, true)
.flush(response.getOutputStream());
} catch (IOException e) {
log.error("导出excel失败", e);
throw new RuntimeException("导出excel失败");
List<PageData> varList = excels.stream().map(excel -> {
PageData data = new PageData();
for (int i = 0; i < HEADER_ALIAS_CACHE.size(); i++) {
data.put("var" + (i + 1), ReflectUtil.getFieldValue(excel, HEADER_ALIAS_CACHE.get(i)));
}
return data;
}).collect(Collectors.toList());
dataMap.put("varList", varList);
return dataMap;
}
@Override
public void importExcel(MultipartFile file) {
// ExecutorType.BATCH: 这个执行器会批量执行所有更新语句。
SqlSession sqlSession = null;
try (ExcelReader reader = ExcelUtil.getReader(file.getInputStream())) {
// 标记别名
HEADER_ALIAS_CACHE.forEach((k, v) -> reader.addHeaderAlias(v, k));
List<AccidentRecordsExcel> recordsExcels = reader.readAll(AccidentRecordsExcel.class);
if (CollUtil.isEmpty(recordsExcels)) {
throw new RuntimeException("没有数据");
}
sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
AccidentRecordsMapper mapper = sqlSession.getMapper(AccidentRecordsMapper.class);
for (int i = 0; i < recordsExcels.size(); i++) {
mapper.save(new AccidentRecords(recordsExcels.get(i), dictionariesService));
if ((i + 1) % 300 == 0 || i == recordsExcels.size() - 1) {
sqlSession.flushStatements();
}
}
// 避免刷新数据字典不生效 每次导出重新查询字典
AccidentRecords.dictMap.clear();
sqlSession.commit();
} catch (RuntimeException e) {
if (sqlSession != null) {
sqlSession.rollback();
}
log.error("导入excel失败", e);
throw e;
} catch (Exception e) {
if (sqlSession != null) {
sqlSession.rollback();
}
log.error("导入excel失败", e);
throw new RuntimeException("导入excel失败");
} finally {
IoUtil.close(sqlSession);
}
}
// @Override
// public void importExcel(MultipartFile file) {
// // ExecutorType.BATCH: 这个执行器会批量执行所有更新语句。
// SqlSession sqlSession = null;
// try (ExcelReader reader = ExcelUtil.getReader(file.getInputStream())) {
// // 标记别名
// HEADER_ALIAS_CACHE.forEach((k, v) -> reader.addHeaderAlias(v, k));
// List<AccidentRecordsExcel> recordsExcels = reader.readAll(AccidentRecordsExcel.class);
// if (CollUtil.isEmpty(recordsExcels)) {
// throw new RuntimeException("没有数据");
// }
// sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
// AccidentRecordsMapper mapper = sqlSession.getMapper(AccidentRecordsMapper.class);
// for (int i = 0; i < recordsExcels.size(); i++) {
// mapper.save(new AccidentRecords(recordsExcels.get(i), dictionariesService));
// if ((i + 1) % 300 == 0 || i == recordsExcels.size() - 1) {
// sqlSession.flushStatements();
// }
// }
// // 避免刷新数据字典不生效 每次导出重新查询字典
// AccidentRecords.dictMap.clear();
// sqlSession.commit();
// } catch (RuntimeException e) {
// if (sqlSession != null) {
// sqlSession.rollback();
// }
// log.error("导入excel失败", e);
// throw e;
// } catch (Exception e) {
// if (sqlSession != null) {
// sqlSession.rollback();
// }
// log.error("导入excel失败", e);
// throw new RuntimeException("导入excel失败");
// } finally {
// IoUtil.close(sqlSession);
// }
// }
@Override
public String importPhotos(MultipartFile file) {

View File

@ -267,27 +267,31 @@
</foreach>
</update>
<select id="listExcel" resultType="com.zcloud.entity.accident.dto.AccidentRecordsExcel">
select incident_number,
incident_name,
(select NAME from sys_dictionaries
where DICTIONARIES_ID = '8d4140a900184b60836ad1a6490fd510' and BIANMA = incident_type) as 'incidentType',
(select NAME from sys_dictionaries
where DICTIONARIES_ID = 'b61a1edc59c0430c8741c5f51aa26c3c' and BIANMA = incident_level) as 'incidentLevel',
<select id="listExcel" resultType="com.zcloud.entity.accident.dto.AccidentRecordsExcel" parameterType="pd">
select incident_number as incidentNumber,
incident_name as incidentName,
(select NAME
from sys_dictionaries
where PARENT_ID = '8d4140a900184b60836ad1a6490fd510'
and BIANMA = incident_type) as 'incidentType',
(select NAME
from sys_dictionaries
where PARENT_ID = 'b61a1edc59c0430c8741c5f51aa26c3c'
and BIANMA = incident_level) as 'incidentLevel',
CORP_NAME as 'companyName',
incident_nature ,
`location`,
incident_nature as incidentNature,
`location` as location,
date_format(incident_date, '%Y年%m月%d日%H时%I分%s秒') as 'incidentDate',
direct_loss,
direct_loss as directLoss,
injured,
fatalities,
seriously_injured,
seriously_injured as seriouslyInjured,
cause,
summary,
analysis,
suggestions,
measures,
ar.creator,
ar.creator as creator,
date_format(report_date, '%Y年%m月%d日%H时%I分%s秒') as 'reportDate'
from accident_records as ar
left join bus_corp_info as bci on ar.corpinfo_id = bci.CORPINFO_ID

View File

@ -111,7 +111,7 @@ public class AccidentRecordsServiceTest {
when(accidentRecordsMapper.listExcel(pd)).thenReturn(expectedList);
HttpServletResponse response = mock(HttpServletResponse.class);
accidentRecordsService.exportExcel(pd, response);
//accidentRecordsService.exportExcel(pd, response);
verify(response, times(1)).setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
verify(response, times(1)).setCharacterEncoding("utf-8");