package com.linghu.service; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.read.listener.ReadListener; import com.linghu.model.entity.Platform; import com.linghu.model.entity.Type; import com.linghu.model.excel.PlatformExcel; import com.linghu.service.TypeService; import com.linghu.service.PlatformService; import org.springframework.beans.factory.annotation.Autowired; 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.net.URLEncoder; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service public class PlatformExcelService { @Autowired private PlatformService platformService; @Autowired private TypeService typeService; /** * 下载平台导入模板 */ public void downloadTemplate(HttpServletResponse response) throws IOException { response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); String fileName = URLEncoder.encode("平台导入模板", "UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx"); EasyExcel.write(response.getOutputStream(), PlatformExcel.class).sheet("平台信息").doWrite(new ArrayList<>()); } /** * 导入平台信息 */ @Transactional(rollbackFor = Exception.class) public void importPlatform(MultipartFile file) throws IOException { EasyExcel.read(file.getInputStream(), PlatformExcel.class, new ReadListener() { private List platforms = new ArrayList<>(); @Override public void invoke(PlatformExcel data, AnalysisContext context) { // 根据类型名称获取类型ID Type type = typeService.getTypeByName(data.getType_name()); if (type == null) { throw new RuntimeException("类型名称不存在:" + data.getType_name()); } Platform platform = new Platform(); platform.setPlatform_name(data.getPlatform_name()); platform.setDomain(data.getDomain()); platform.setType_id(type.getType_id()); platform.setCreate_time(LocalDateTime.now()); platforms.add(platform); // 每100条保存一次 if (platforms.size() >= 100) { saveData(); platforms.clear(); } } @Override public void doAfterAllAnalysed(AnalysisContext context) { saveData(); } private void saveData() { if (!platforms.isEmpty()) { platformService.saveBatch(platforms); } } }).sheet().doRead(); } }