Java 導出CSV格式數據

  • 工具類

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 = "下載到本地的文件路徑(默認爲downloads路徑)", required = true)
                                   @RequestParam(value = "filePath", required = true) String filePath,
                                   @ApiParam(value = "文件名(後綴爲.csv)", required = true)
                                   @RequestParam(value = "fileName", required = true) String fileName) throws Exception {
            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();
                }
            }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章