欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 导出CSV格式数据

程序员文章站 2024-03-20 21:10:04
...
  • 工具类

import java.io.*;
import java.util.List;

/**
 * CSV文件导出工具类
 */
@Component
public class CSVUtil {

    /**
     * CSV文件生成方法
     */
    public File createCSVFile(List<Object> head, List<List<Object>> dataList,
                              String outPutPath, String filename) {

        File csvFile = null;
        BufferedWriter csvWtriter = null;
        try {
            csvFile = new File(outPutPath + File.separator + filename + ".csv");
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();

            // GB2312使正确读取分隔符","
            csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                    csvFile), "GB2312"), 1024);
            // 写入文件头部
            writeRow(head, csvWtriter);

            // 写入文件内容
            for (List<Object> row : dataList) {
                writeRow(row, csvWtriter);
            }
            csvWtriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (csvWtriter != null) {
                    csvWtriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return csvFile;
    }

    /**
     * 写一行数据方法=
     */
    private void writeRow(List<Object> row, BufferedWriter csvWriter) throws IOException {
        // 写入文件头部
        for (Object data : row) {
            StringBuffer sb = new StringBuffer();
            String rowStr = sb.append("\"").append(data).append("\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }
}

如果是web端,需要加如下代码

public void exportCSV(HttpServletRequest request, HttpServletResponse response,
                                   @ApiParam(value = "文件名", required = true)
                                   @RequestParam(value = "fileName", required = true) String fileName) throws Exception {
            /**
             * 远程下载,这个没用,无需配置
             * 运行test的时候可以用
             */
            String filePath = "";
            File csvFile = ...//这里是CSVUtil 生成的csv文件

            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(csvFile.getName(), "UTF-8"));
                response.setHeader("Content-Length", String.valueOf(csvFile.length()));
                bis = new BufferedInputStream(new FileInputStream(csvFile));
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                while (true) {
                    int bytesRead;
                    if (-1 == (bytesRead = bis.read(buff, 0, buff.length))) {
                        break;
                    }
                    bos.write(buff, 0, bytesRead);
                }
            } catch (Exception e) {
                throw new ServiceException(e.getMessage());
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            }
    }