spring生成csv文件并压缩工具

引入CSV依赖

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>1.8</version>
</dependency>

直接上util

package com.yumc.recipecenter.sortservice.export.utils;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author shangxichen
 * @date 2020-03-18
 */
public class GenerateFileUtil {
    private final static Logger logger = LoggerFactory.getLogger(GenerateFileUtil.class);

    private final static char CSV_RECORD_SEPARATE = '\n';

    /**
     * 压缩入口
     * @param path
     * @param directoryName
     */
    public static void generateZip(String path, String directoryName) {
        File srcPath = new File(path + directoryName);
        File zipFile = new File(path + directoryName + ".zip");
        try {
            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);
            String baseDir = "";
            compressbyType(srcPath, zos, baseDir);
            zos.close();

        } catch (Exception e) {
            logger.error("压缩" + directoryName + "失败");
        }
    }

    private static void compressbyType(File src, ZipOutputStream zos, String baseDir) {

        if (!src.exists()) {
            return;
        }
        logger.info("压缩路径:" + baseDir + src.getName());
        //判断文件是否是文件,如果是文件调用compressFile方法,如果是路径,则调用compressDir方法;
        if (src.isFile()) {
            //src是文件,调用此方法
            compressFile(src, zos, baseDir);

        } else if (src.isDirectory()) {
            //src是文件夹,调用此方法
            compressDir(src, zos, baseDir);

        }

    }

    /**
     * 压缩文件
     */
    private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
        if (!file.exists()) {
            return;
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry = new ZipEntry(baseDir + file.getName());
            zos.putNextEntry(entry);
            int count;
            byte[] buf = new byte[1024];
            while ((count = bis.read(buf)) != -1) {
                zos.write(buf, 0, count);
            }
            bis.close();

        } catch (Exception e) {
            logger.error("压缩:" + file.getName() + "失败");
        }
    }

    /**
     * 压缩文件夹
     */
    private static void compressDir(File dir, ZipOutputStream zos, String baseDir) {
        if (!dir.exists()) {
            return;
        }
        File[] files = dir.listFiles();
        if (files.length == 0) {
            try {
                zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
            } catch (IOException e) {
                logger.error("压缩文件夹:" + dir.getName() + "失败");
            }
        }
        for (File file : files) {
            compressbyType(file, zos, baseDir + dir.getName() + File.separator);
        }
    }


    /**
     * 生成CSV文件
     * @param path 生成文件所在路径
     * @param fileName  生成文件名
     * @param header csv文件头部
     * @param dataList 数据
     * @throws IOException
     */
    public static void generateCsv(String path, String fileName, String[] header, List dataList) throws IOException {
        File desPath = new File(path);
        if (!desPath.exists()) {
            desPath.mkdirs();
        }
        Appendable out = new PrintWriter(path + fileName);
        CSVPrinter csvPrinter = CSVFormat.DEFAULT.withHeader(header).withRecordSeparator(CSV_RECORD_SEPARATE).print(out);
        for (Object obj : dataList) {
            csvPrinter.printRecord(obj.toString());
        }
        logger.info("生成" + fileName + "成功");
        csvPrinter.flush();
        csvPrinter.close();
    }
}

调用工具的serviceimpl

package com.yumc.recipecenter.sortservice.export.service.impl;

import com.yumc.recipecenter.sortservice.export.common.ExportConstant;
import com.yumc.recipecenter.sortservice.export.dao.ExportMapper;
import com.yumc.recipecenter.sortservice.export.entity.ProductInfoEntity;
import com.yumc.recipecenter.sortservice.export.entity.ProductRecipeRelationEntity;
import com.yumc.recipecenter.sortservice.export.entity.RecipeBasicMaterialRelationEntity;
import com.yumc.recipecenter.sortservice.export.entity.ReleaseDescriptionEntity;
import com.yumc.recipecenter.sortservice.export.service.ExportService;
import com.yumc.recipecenter.sortservice.export.utils.GenerateFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author shangxichen
 * @date 2020-03-18
 */
@Service
public class ExportServiceImpl implements ExportService, ExportConstant {

    private final Logger logger = LoggerFactory.getLogger(ExportServiceImpl.class);
    @Resource
    private ExportMapper exportMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public String findDataToZip(String storeCode) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String directoryName = simpleDateFormat.format(date) + '_' + storeCode;
//        List<ProductInfoEntity> productInfoEntityList = exportMapper.selectProductInfoByStore(storeCode);
        List<ProductRecipeRelationEntity> productRecipeRelationEntityList = exportMapper.selectProductRecipeRelationByStore(storeCode);
        List<RecipeBasicMaterialRelationEntity> recipeBasicMaterialRelationEntityList = exportMapper.selectRecipeBasicMaterialRelationByStore(storeCode);
        List<ReleaseDescriptionEntity> releaseDescriptionEntityList = exportMapper.selectReleaseDescriptionByStore(storeCode);
        List<ProductInfoEntity> productInfoEntityList = new ArrayList<>();
        productInfoEntityList.add(new ProductInfoEntity());
        try {
            String csvPath = DIRETORY_PATH + directoryName + '/';
            GenerateFileUtil.generateCsv(csvPath, PRODUCT_INFO_CSV, PRODUCT_INFO_CSV_HEADER, productInfoEntityList);
            GenerateFileUtil.generateCsv(csvPath, PRODUCT_RECIPE_RELETION_CSV, PRODUCT_RECIPE_RELETION_CSV_HEADER, productRecipeRelationEntityList);
            GenerateFileUtil.generateCsv(csvPath, RECIPE_BASIC_MATERIAL_RELATION_CSV, RECIPE_BASIC_MATERIAL_RELATION_CSV_HEADER, recipeBasicMaterialRelationEntityList);
            GenerateFileUtil.generateCsv(csvPath, RELEAS_EDESCRIPTION_CSV, RELEASE_DESCRIPTION_CSV_HEADER, releaseDescriptionEntityList);
            GenerateFileUtil.generateZip(DIRETORY_PATH, directoryName);
        } catch (IOException e) {
            logger.error("生成zip失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return DIRETORY_PATH + directoryName + ".zip";
    }
}

相关常量接口

package com.yumc.recipecenter.sortservice.export.common;

import org.springframework.beans.factory.annotation.Value;

/**
 * @author shangxichen
 * @date 2020-03-19
 */
public interface ExportConstant {

    /**
     * epqc zip 下发常量
     */
    String RELEAS_EDESCRIPTION_CSV = "release_description.csv";

    String[] RELEASE_DESCRIPTION_CSV_HEADER = {"version_no", "business_date"};

    String PRODUCT_INFO_CSV = "product_info.csv";

    String[] PRODUCT_INFO_CSV_HEADER = {"product_code", "product_name", "product_name_first_letter", "product_class_code", "on_market_date", "out_market_date", "is_need_maintenance_sop", "sale_times", "product_cost", "daypart_dinner_code"};

    String PRODUCT_RECIPE_RELETION_CSV = "product_recipe_relation.csv";

    String[] PRODUCT_RECIPE_RELETION_CSV_HEADER = {"product_code", "product_recipe_code", "product_recipe_name", "effective_begin_date"};

    String RECIPE_BASIC_MATERIAL_RELATION_CSV = "recipe_basic_material_relation.csv";

    String[] RECIPE_BASIC_MATERIAL_RELATION_CSV_HEADER = {"product_code", "product_recipe_code", "basicmaterial_code", "basicmaterial_amount"};

    String DIRETORY_PATH = "C:/work/epqc/";


}
发布了18 篇原创文章 · 获赞 0 · 访问量 1989

猜你喜欢

转载自blog.csdn.net/rye1009/article/details/104984491