guyue
4 天以前 c3f9a20ad3d4615953c04f55b3080148738446ee
src/main/java/com/linghu/controller/KeywordController.java
@@ -1,10 +1,16 @@
package com.linghu.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.linghu.listener.KeywordExcelListener;
import com.linghu.mapper.KeywordMapper;
import com.linghu.model.common.ResponseResult;
import com.linghu.model.entity.Keyword;
import com.linghu.model.entity.Reference;
import com.linghu.model.excel.KeywordExcel;
import com.linghu.model.excel.PlatformExcel;
import com.linghu.model.vo.KeywordStaticsListVO;
import com.linghu.model.vo.KeywordStaticsVO;
import com.linghu.model.vo.PlatformProportionVO;
@@ -17,10 +23,13 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@@ -202,4 +211,40 @@
        return ResponseResult.success("删除成功");
    }
    // 下载模板
    @PostMapping("/downloadTemplate")
    @ApiOperation("下载模板")
    public ResponseEntity<byte[]> downloadTemplate() throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        EasyExcel.write(out, KeywordExcel.class).sheet("关键词模板").doWrite(new ArrayList<>());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=keyword_template.xlsx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(out.toByteArray());
    }
    // 导入文件
    @PostMapping("/import")
    @ApiOperation("导入关键词数据")
    public ResponseResult<String> importPlatforms(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseResult.error("上传文件不能为空");
            }
            // 创建数据监听器
            KeywordExcelListener listener = new KeywordExcelListener();
            EasyExcel.read(file.getInputStream(), KeywordExcel.class, listener)
                    .sheet()
                    .doRead();
            // 获取并合并关键词
            String mergedKeywords = String.join("\n", listener.getMergedKeywords());
            return ResponseResult.success(mergedKeywords);
        } catch (IOException e) {
            return ResponseResult.error("文件读取失败:" + e.getMessage());
        } catch (Exception e) {
            return ResponseResult.error("导入失败:" + e.getMessage());
        }
    }
}