创建csv文件

发布时间 2023-08-02 09:49:28作者: 新手娃娃菜
    /**
     * 创建csv文件
     * @param titles 标题
     * @param contents 内容
     * @param destPath 文件写出路径
     * @param fileName 文件名称
     */
    private void createCsvFile(String[] titles, List<String[]> contents, 
        String destPath, String fileName){
        if(destPath==null||destPath.trim().length()==0){
            logger.error("文件输出路径为空");
            return;
        }
        if(fileName==null||fileName.trim().length()==0){
            logger.error("文件输出名称为空");
            return;
        }
        if(titles==null||titles.length==0){
            logger.error("文件标题为空");
            return;
        }
        if(contents!=null&&contents.size()>0){
            String[] lineContent = contents.get(0);
            if(lineContent.length!=titles.length){
                logger.error("文件标题和数据长度不一致,请检查");
                return;
            }
        }
        
        if(!destPath.endsWith(File.separator)){
            destPath += File.separator;
        }
        
        String filePath = destPath + fileName;
        File file = new File(filePath);
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(file));
            StringBuffer fileBuffer = new StringBuffer();
            //标题
            StringBuffer titleBuffer = new StringBuffer();
            for(int i=0;i<titles.length;i++){
                titleBuffer.append("\"");
                titleBuffer.append(titles[i]);
                titleBuffer.append("\"");
                if(i<titles.length-1){
                    titleBuffer.append(",");
                }
            }
            fileBuffer.append(titleBuffer.toString());
            
            //内容
            if(contents!=null&&contents.size()>0){
                StringBuffer contentBuffer = new StringBuffer();
                contentBuffer.append("\r\n");
                for(int i=0;i<contents.size();i++){
                    String[] lineContent = contents.get(i);
                    for(int j=0;j<lineContent.length;j++){
                        contentBuffer.append("\"");
                        contentBuffer.append(lineContent[j]);
                        contentBuffer.append("\"");
                        if(j<lineContent.length-1){
                            contentBuffer.append(",");
                        }
                    }
                    if(i<contents.size()-1){
                        contentBuffer.append("\r\n");
                    }
                }
                fileBuffer.append(contentBuffer.toString());
            }
            bw.write(fileBuffer.toString());
            bw.flush();
            logger.info(filePath+"文件写出正常");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }