whycxzp
2024-09-06 05aebb26d1e2e1fbaebe0119876aa97caea1fef5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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 {
 
    @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;
 
    }
}