其他分享
首页 > 其他分享> > 文件导出CSV

文件导出CSV

作者:互联网

大文件的导出 csv

  1. jar包的导入
 <!--csv文件下载-->
        <dependency>
            <groupId>net.sourceforge.javacsv</groupId>
            <artifactId>javacsv</artifactId>
            <version>2.0</version>
        </dependency>

2.csv工具

import com.csvreader.CsvWriter;


import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.net.URLEncoder;
import java.nio.charset.Charset;

/**
 * @author 
 * @date 2021/3/31 0031 18:33
 */
public class CsvUtil {

    public interface WriteCsv {
        void write(CsvWriter csvWriter) throws Exception;
    }

    public static void writeCsv(String fileName,HttpServletResponse response, CsvUtil.WriteCsv writeCsv){

        try {
            // 创建临时文件
            File tempfile = File.createTempFile(fileName, ".csv");

            // 创建 CsvWriter 对象
            CsvWriter csvWriter = new CsvWriter(tempfile.getCanonicalPath(),',', Charset.forName("GBK"));

            // 接口需要实现的方法
            writeCsv.write(csvWriter);

            // 关闭 CsvWriter 对象
            csvWriter.close();

            // 获取写入数据的临时文件
            File fileLoad=new File(tempfile.getCanonicalPath());

            // 返回给前端
            CsvUtil.downLoadCsv(fileName+".csv", fileLoad,response);

            // 在项目中生成文件
//            CsvUtil.downLoadCsvHere(fileName+".csv", fileLoad);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 在项目中生成文件
     * @param fileName
     * @param fileLoad
     */
    public static void downLoadCsvHere(String fileName, File fileLoad){
        try {
            byte[] b=new byte[1024];
            FileOutputStream out = new FileOutputStream(fileName);
            FileInputStream fileInputStream=new FileInputStream(fileLoad);
            int n;
            while ((n = fileInputStream.read(b)) != -1) {
                out.write(b, 0, n); //每次写入out1024字节
            }
            fileInputStream.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 返回给前端
     * @param fileName
     * @param fileLoad
     * @param response
     */
    public static void downLoadCsv(String fileName, File fileLoad, HttpServletResponse response) {
        try {
            byte[] b = new byte[1024];
            OutputStream out = response.getOutputStream();
            response.reset();
            response.setContentType("application/csv");
            response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            Long filelength = fileLoad.length();
            response.setHeader("Content_Length", String.valueOf(filelength));
            FileInputStream fileInputStream = new FileInputStream(fileLoad);
            int n;
            while ((n = fileInputStream.read(b)) != -1) {
                out.write(b, 0, n); //每次写入out1024字节
            }
            fileInputStream.close();
            out.close();
        } catch (IOException e) {
            try {
                throw new Exception(e.getMessage());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
}

3.调用示例

 public String downUrl(String examId, String type) throws IOException {
        List<BksTemVO> listExam;
        if ("1".equals(type)) {
            //查询分数列表
            List<BksScoresTemporary> listOld = bksScoresTemporaryService.lambdaQuery().eq(BksScoresTemporary::getExamId, examId).list();
            listExam = JSON.parseArray(JSON.toJSONString(listOld), BksTemVO.class);
        } else {
            List<BksScoresTemporaryNew> listNew = bksScoresTemporaryNewService.lambdaQuery().eq(BksScoresTemporaryNew::getExamId, examId).list();
            listExam = JSON.parseArray(JSON.toJSONString(listNew), BksTemVO.class);
        }

        String[] titles = new String[]{"考试代码","学籍号","姓名","区县名称","区县原始名称","区县代码","学校名称",
                "学校原始名称","学校代码","班级","语文","数学","英语","物理","历史","化学","生物","政治","地理",
                "学科组合代码","学科组合名称","学科组合原始名称"}; // 导出列标题

        // 调用service层获取list集合;
        CsvUtil.writeCsv(examId+"分数"+type, response, new CsvUtil.WriteCsv() {
            @Override
            public void write(CsvWriter csvWriter) throws Exception {
                csvWriter.writeRecord(titles);
                if (listExam!=null && !listExam.isEmpty()){
                    // 遍历List集合,将每条数据对应写入
                    for (BksTemVO data:listExam) {
                        csvWriter.write(data.getExamId());
                        csvWriter.write(data.getStudentCode());
                        csvWriter.write(data.getStudentName());
                        csvWriter.write(data.getDistrictName());
                        csvWriter.write(data.getDistrictNameTemp());
                        csvWriter.write(data.getDistrictId());
                        csvWriter.write(data.getUnitName());
                        csvWriter.write(data.getUnitNameTemp());
                        csvWriter.write(data.getUnitId());
                        csvWriter.write(data.getClassName());
                        csvWriter.write(data.getChinese());
                        csvWriter.write(data.getMathematics());
                        csvWriter.write(data.getEnglish());
                        csvWriter.write(data.getPhysical());
                        csvWriter.write(data.getHistory());
                        csvWriter.write(data.getChemical());
                        csvWriter.write(data.getBiological());
                        csvWriter.write(data.getPolitical());
                        csvWriter.write(data.getGeographic());
                        csvWriter.write(data.getSubjectCombId());
                        csvWriter.write(data.getSubjectCombName());
                        csvWriter.write(data.getSubjectCombNameTemp());
                        csvWriter.endRecord();
                    }
                }
            }
        });
        return  null;
    }

备注:之前使用easyExcel、POI导出到时数据量较大时会出现不确定问题(自己没能解决),后换成csv

标签:文件,data,fileLoad,导出,fileName,write,new,CSV,csvWriter
来源: https://blog.csdn.net/L1569850979/article/details/115372234