Bladeren bron

jxls自测

chengang 4 jaren geleden
bovenliggende
commit
eb92cc4329

+ 49 - 0
src/main/java/com/aoyang/tms/controller/JxlsExportTestController.java

@@ -0,0 +1,49 @@
+package com.aoyang.tms.controller;
+
+import com.alibaba.fastjson.JSON;
+import com.aoyang.tms.entity.TmsGasFee;
+import com.aoyang.tms.service.JxlsExportTestService;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * <p>
+ * 车辆行车日志表 控制器
+ * </p>
+ *
+ * @author guoyong
+ * @since 2022-04-20
+ */
+@RestController
+@Slf4j
+@Api(value = "行车日志相关接口")
+@RequestMapping("/tms/jxls_export")
+public class JxlsExportTestController {
+
+    @Resource
+    private JxlsExportTestService jxlsExportTestService;
+
+    @ApiOperation(value = "下载行车日志,测试自用")
+    @PostMapping("/download_test")
+    public StreamingResponseBody download(HttpServletResponse response, @RequestBody TmsGasFee param) {
+        log.info("下载行车日志,导出专用,调用/tms/jxls_export/download_test,参数:{}", JSON.toJSONString(param));
+        if (null == param) {
+            log.error("download_list param is null");
+        }
+        try {
+            return jxlsExportTestService.download(param, response);
+        } catch (Exception e) {
+            log.error("download_list " + e.getMessage() + ":{}", e);
+        }
+        return null;
+    }
+}

+ 60 - 0
src/main/java/com/aoyang/tms/controller/vo/WorkLogTplVO.java

@@ -0,0 +1,60 @@
+package com.aoyang.tms.controller.vo;
+
+import com.aoyang.tms.entity.TmsGasFee;
+import com.aoyang.tms.entity.TmsOtherFee;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+import java.time.LocalDateTime;
+import java.util.List;
+
+@Data
+public class WorkLogTplVO {
+
+    @ApiModelProperty(value = "线路费用列表")
+    private List<TmsLineCostDetail> tmsLineCostList;
+
+    @ApiModelProperty(value = "燃气费用列表")
+    private List<TmsGasFee> tmsGasFeeList;
+
+    @ApiModelProperty(value = "其他费用列表")
+    private TmsOtherFee tmsOtherFee;
+
+    @ApiModelProperty(value = "车牌号")
+    private String carNumber;
+
+    @ApiModelProperty(value = "挂车车牌号")
+    private String trailerNumber;
+
+    @ApiModelProperty(value = "行车日志表头日期")
+    private String logDate;
+
+    @ApiModelProperty(value = "司机1姓名")
+    private String driverNameOne;
+
+    @ApiModelProperty(value = "司机2姓名")
+    private String driverNameTwo;
+
+    @ApiModelProperty(value = "押运员姓名")
+    private String escortName;
+
+    @ApiModelProperty(value = "开始公里数")
+    private Integer startKilometre;
+
+    @ApiModelProperty(value = "结束公里数")
+    private Integer endKilometre;
+
+    @ApiModelProperty(value = "总共公里数")
+    private Integer sumKilometre;
+
+    @ApiModelProperty(value = "开始时间")
+    private LocalDateTime startTime;
+
+    @ApiModelProperty(value = "结束时间")
+    private LocalDateTime endTime;
+
+    @ApiModelProperty(value = "总计时间")
+    private String betweenTime;
+}

+ 20 - 0
src/main/java/com/aoyang/tms/service/JxlsExportTestService.java

@@ -0,0 +1,20 @@
+package com.aoyang.tms.service;
+
+import com.aoyang.tms.entity.TmsGasFee;
+import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+
+public interface JxlsExportTestService {
+
+    /**
+     * @return
+     * @Author chengang
+     * @Description 下载行车日志,财务导出专用
+     * @Date 2022/4/13
+     * @Param
+     **/
+    StreamingResponseBody download(TmsGasFee param, HttpServletResponse response) throws IOException;
+}

+ 97 - 0
src/main/java/com/aoyang/tms/service/impl/JxlsExportTestServiceImpl.java

@@ -0,0 +1,97 @@
+package com.aoyang.tms.service.impl;
+
+
+import com.aoyang.tms.entity.TmsGasFee;
+import com.aoyang.tms.service.CommonService;
+import com.aoyang.tms.service.JxlsExportTestService;
+import com.aoyang.tms.service.TmsGasFeeService;
+import com.aoyang.tms.util.FileUtil;
+import com.aoyang.tms.util.JxlsUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.FileUtils;
+import org.springframework.stereotype.Service;
+import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Service
+@Slf4j
+public class JxlsExportTestServiceImpl implements JxlsExportTestService {
+
+    @Resource
+    private TmsGasFeeService tmsGasFeeService;
+
+    @Override
+    public StreamingResponseBody download(TmsGasFee param, HttpServletResponse response) throws IOException {
+
+
+        TmsGasFee tmsGasFee = tmsGasFeeService.getById(param);
+        byte imageBytes[] = getImageBytes("/cn/chendd/examples/images/splash.jpg");
+
+        // 获取模板文件
+        String tplfileName = "circle_sign_tpl.xlsx";
+        String tmpFileName = FileUtil.getTmpFileName(FileUtil.getFilePrefix(tplfileName));
+        String tmpFilePath = FileUtils.getTempDirectoryPath() + File.separator + tmpFileName;
+        // 写文件
+        OutputStream os = new FileOutputStream(tmpFilePath);
+        InputStream inputStream = FileUtil.getFileTplInputStream(tplfileName);
+        log.info("tmpFilePath :{}", tmpFilePath);
+        log.info("tplfileName :{}", tplfileName);
+        if (os != null && inputStream != null) {
+            Map<String, Object> model = new HashMap<String, Object>();
+            model.put("tmsGasFee", tmsGasFee);
+            JxlsUtils.exportExcel(inputStream, os, model);
+            os.close();
+        }
+        // 导出
+        String newFileName = "circleSign.xlsx";
+        // 输出文件
+        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", newFileName));
+
+        response.setHeader("content-type", "application/octet-stream");
+        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(new File(tmpFilePath)));
+        return new StreamingResponseBody() {
+            @Override
+            public void writeTo(OutputStream outputStream) throws IOException {
+                int nRead;
+                long startTime = System.currentTimeMillis();
+
+                byte[] bytes = new byte[1024];
+                while ((nRead = bufferedInputStream.read(bytes, 0, bytes.length)) != -1) {
+                    outputStream.write(bytes, 0, nRead);
+                }
+                long userTime = System.currentTimeMillis() - startTime;
+                log.info("orgAccountLogList使用时间" + userTime);
+            }
+        };
+
+    }
+
+    //获取图片的字节码,临时使用
+    private static byte[] getImageBytes(String imagePath) throws IOException {
+        byte imageBytes[] = null;
+        InputStream is = JxlsExportTestServiceImpl.class.getClass().getResourceAsStream(imagePath);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        byte bytes[] = new byte[1024];
+        int lens = -1;
+        try {
+            while ((lens = is.read(bytes)) != -1) {
+                baos.write(bytes, 0, lens);
+            }
+            imageBytes = baos.toByteArray();
+        } catch (IOException e) {
+            throw new IOException(e);
+        } finally {
+            baos.flush();
+            baos.close();
+            is.close();
+        }
+        return imageBytes;
+    }
+}

+ 171 - 0
src/main/java/com/aoyang/tms/util/FileUtil.java

@@ -0,0 +1,171 @@
+package com.aoyang.tms.util;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.core.io.ClassPathResource;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+/**
+ * @Description: ${DESCRIPTION}
+ * @Author guoyong
+ * @Date 2020/12/24 10:32
+ * @Version 1.0
+ */
+public class FileUtil {
+
+    private static final boolean isWin = System.getProperty("os.name").toLowerCase().contains("win");
+
+    private static final boolean isLinux = System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0;
+
+    /**
+     * @return
+     * @Author guoyong
+     * @Description /获取临时文件路径
+     * @Date 2020/12/25
+     * @Param
+     **/
+    public static String getTempDirectoryPath() {
+        if (isWin) {
+            return FileUtils.getTempDirectoryPath();
+        }
+        if (isLinux) {
+            return "/tmp/";
+        }
+        return "";
+    }
+
+    public static void main(String[] args) {
+
+        String path = "image/M00/00/34/rB86LWDQM6-AZo1RAADrnf2b4e0334.pdf";
+        System.out.println(getFileNameFromPath(path));
+
+
+    }
+
+    /**
+     * @return
+     * @Author guoyong
+     * @Description 根据文件路径获取文件名
+     * @Date 2021/6/21
+     * @Param
+     **/
+    public static String getFileNameFromPath(String path) {
+        String fileName = FilenameUtils.getName(path);
+        return fileName;
+    }
+
+    /**
+     * @return
+     * @Author guoyong
+     * @Description 远程URL获取inputstream
+     * @Date 2021/6/21
+     * @Param
+     **/
+    public static InputStream URL2InputStream(URL url) {
+        InputStream inputStream = null;
+        try {
+            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+            //设置超时间为3秒
+            conn.setConnectTimeout(3 * 1000);
+            //防止屏蔽程序抓取而返回403错误
+            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
+            //得到输入流
+            inputStream = conn.getInputStream();
+
+        } catch (MalformedURLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return inputStream;
+    }
+
+    /**
+     * @return
+     * @Author guoyong
+     * @Description 获取文件名前缀
+     * @Date 2020/12/24
+     * @Param
+     **/
+    public static String getFilePrefix(String fileName) {
+        if (StringUtils.isBlank(fileName)) {
+            return "";
+        }
+        String prefix = fileName.substring(0, fileName.lastIndexOf("."));
+        return prefix;
+    }
+
+    /**
+     * @return
+     * @Author guoyong
+     * @Description 获取文件名后缀
+     * @Date 2020/12/24
+     * @Param
+     **/
+    public static String getFileSuffix(String fileName) {
+        if (StringUtils.isBlank(fileName)) {
+            return "";
+        }
+        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
+        return suffix;
+    }
+
+    /**
+     * @return
+     * @Author guoyong
+     * @Description 根据获取临时文件名
+     * @Date 2020/12/24
+     * @Param
+     **/
+    public static String getTmpFileName(String tplfileName) {
+        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssS");
+        String tmpFileName = tplfileName + "_" + formatter.format(new Date()) + ".xlsx";
+        return tmpFileName;
+    }
+
+    /**
+     * @return
+     * @Author guoyong
+     * @Description 获取模板文件的File
+     * @Date 2020/12/24
+     * @Param
+     **/
+    public static File getFileTpl(String tplfileName) {
+        File tplFile = null;
+        ClassPathResource classPathResource = new ClassPathResource("exceltpl/" + tplfileName);
+        try {
+            tplFile = classPathResource.getFile();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return tplFile;
+    }
+
+    /**
+     * @return
+     * @Author guoyong
+     * @Description 获取模板文件的InputStream
+     * @Date 2020/12/24
+     * @Param
+     **/
+    public static InputStream getFileTplInputStream(String tplfileName) {
+        InputStream tplInputStream = null;
+        ClassPathResource classPathResource = new ClassPathResource("exceltpl/" + tplfileName);
+        try {
+            tplInputStream = classPathResource.getInputStream();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return tplInputStream;
+    }
+
+}

+ 136 - 0
src/main/java/com/aoyang/tms/util/JxlsUtils.java

@@ -0,0 +1,136 @@
+package com.aoyang.tms.util;
+
+import org.jxls.common.Context;
+import org.jxls.expression.JexlExpressionEvaluator;
+import org.jxls.transform.Transformer;
+import org.jxls.transform.poi.PoiTransformer;
+import org.jxls.util.JxlsHelper;
+
+import java.io.*;
+import java.math.BigDecimal;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.HashMap;
+import java.util.Map;
+
+public class JxlsUtils {
+
+    public static void exportExcel(InputStream is, OutputStream os, Map<String, Object> model) throws IOException {
+        Context context = PoiTransformer.createInitialContext();
+        if (model != null) {
+            for (String key : model.keySet()) {
+                context.putVar(key, model.get(key));
+            }
+        }
+        JxlsHelper jxlsHelper = JxlsHelper.getInstance();
+        Transformer transformer = jxlsHelper.createTransformer(is, os);
+        //获得配置
+        JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
+        //设置静默模式,不报警告
+        //evaluator.getJexlEngine().setSilent(true);
+        //函数强制,自定义功能
+        Map<String, Object> funcs = new HashMap<String, Object>();
+        funcs.put("utils", new JxlsUtils());    //添加自定义功能
+        evaluator.getJexlEngine().setFunctions(funcs);
+        //必须要这个,否则表格函数统计会错乱
+        jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
+    }
+
+    public static void exportExcel(File xls, File out, Map<String, Object> model) throws FileNotFoundException, IOException {
+        exportExcel(new FileInputStream(xls), new FileOutputStream(out), model);
+    }
+
+    public static void exportExcel(String templatePath, OutputStream os, Map<String, Object> model) throws Exception {
+        File template = getTemplate(templatePath);
+        if (template != null) {
+            exportExcel(new FileInputStream(template), os, model);
+        } else {
+            throw new Exception("Excel 模板未找到。");
+        }
+    }
+
+    //获取jxls模版文件
+    public static File getTemplate(String path) {
+        File template = new File(path);
+        if (template.exists()) {
+            return template;
+        }
+        return null;
+    }
+
+    /**
+     * @return
+     * @Author
+     * @Description 计算 单位利润额
+     * @Date 2021/1/5
+     * @Param
+     **/
+    public static BigDecimal caculateGwayPrice(BigDecimal gwayprice) {
+        try {
+            BigDecimal bignum2 = new BigDecimal("1000");
+            BigDecimal price = null;
+            price = gwayprice.divide(bignum2);
+            return price;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+    /**
+     * @return
+     * @Author guoyong
+     * @Description Long 2 String
+     * @Date 2020/12/31
+     * @Param
+     **/
+    public static String longToStr(Long value) {
+        if (value == null) {
+            return "";
+        }
+        return String.valueOf(value);
+    }
+
+    // 日期格式化
+    public String dateFmt(LocalDateTime localDateTime, String format) {
+        if (localDateTime == null) {
+            return "";
+        }
+        try {
+            DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern(format);
+            String strDate2 = dtf2.format(localDateTime);
+            return strDate2;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return "";
+    }
+
+
+    // if判断
+    public Object ifelse(boolean b, Object o1, Object o2) {
+        return b ? o1 : o2;
+    }
+
+    /**
+     * @return
+     * @Author guoyong
+     * @Description stock_type to String 库存操作类型 1=入库 2=出库 3=库存调整
+     * @Date 2020/12/31
+     * @Param
+     **/
+    public static String stockTypeToStr(Integer value) {
+        String str = "";
+        if (value == 1) {
+            str = "入库气量";
+        }
+        if (value == 2) {
+            str = "销售气量";
+        }
+        if (value == 3) {
+            str = "库存调整";
+        }
+        return str;
+    }
+}