whycxzp
2024-08-01 52f98f1a31e682f725f09b4a37bcd316332d3131
src/main/java/com/whyc/service/ReportService.java
@@ -1,9 +1,20 @@
package com.whyc.service;
import com.whyc.dto.Response;
import com.whyc.mapper.ReportMapper;
import com.whyc.util.CommonUtil;
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;
@Service
public class ReportService {
@@ -11,4 +22,44 @@
    @Resource
    private ReportMapper mapper;
    @Autowired
    private BattRTStateService battRTStateService;
    public Response<String> generateDocument() throws JAXBException, Docx4JException {
        Response<String> response = new Response<>();
        //获取classpath下的模板
        String templatePath = this.getClass().getClassLoader().getResource("").getPath()+"\\template\\template_01.docx";
        //加载模板
        WordprocessingMLPackage wordprocessingMLPackage = WordprocessingMLPackage.load(new File(templatePath));
        MainDocumentPart documentPart =  wordprocessingMLPackage.getMainDocumentPart();
        //查询巡检时候的电流电压温度数据
        float current = 1.0f;
        float voltage = 2.0f;
        float temperature = 3.0f;
        String reporter = "whyc";
        String inspectionTime = "2020-01-01 00:00:00";
        HashMap<String,String> map = new HashMap<>();
        map.put("current",current+"");
        map.put("voltage",voltage+"");
        map.put("temperature",temperature+"");
        map.put("reporter",reporter);
        map.put("inspectionTime",inspectionTime);
        //替换占位符
        documentPart.variableReplace(map);
        //输出文件名称
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "报告_01_"+format.format(System.currentTimeMillis())+".docx";
        String fileDir = CommonUtil.getRootFile()+"报告";
        File dirFile = new File(fileDir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = fileDir + File.separator + fileName;
        Docx4J.save(wordprocessingMLPackage, new File(filePath));
        response.setCode(1);
        response.setData("\\inspectionSystem_file\\报告\\"+fileName);
        return response;
    }
}