CSV example

Java data model to CSV file

Object -> CSV

 private static void writeToCSV(List apexTestResults)
    {
        try
        {
        	String path = ProjectUser.getPath(Engine.userName)+"testresult.csv";
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8"));
            bw.write(String.join(",",getCSVColumns()));
            bw.newLine();
            for (ApexTestResult apexTestResult : apexTestResults)
            {
                StringBuffer oneLine = new StringBuffer();
                oneLine.append(apexTestResult.getApexClass()==null?"":apexTestResult.getApexClass().getName())
                		.append(apexTestResult.getStackTrace()==null?"-":apexTestResult.getStackTrace());
                bw.write(oneLine.toString());
                bw.newLine();
            }
            bw.flush();
            bw.close();
        }
        catch (Exception e) {
        	e.printStackTrace();
        }
    }

自定义csv content并输出,灵活性不够。

 

JSON -> CSV

private static void convertToCSVFromJson(JSONArray array){
    	try{
    		JsonNode jsonTree = new ObjectMapper().readTree(array.toString());

    		Builder csvSchemaBuilder = CsvSchema.builder();
    		JsonNode firstObject = jsonTree.elements().next();
    		firstObject.fieldNames().forEachRemaining(fieldName -> csvSchemaBuilder.addColumn(fieldName));
    		CsvSchema csvSchema = csvSchemaBuilder.build().withHeader();

    		CsvMapper csvMapper = new CsvMapper();
    		csvMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    		csvMapper.writerFor(JsonNode.class)
    		.with(csvSchema)
    		.writeValue(new File("testresult.csv"), jsonTree);
    	}catch(IOException e){
    		e.printStackTrace();
    		ErrorModel.insertErrorMsg(e.getMessage());
    	}
    }

Dependency


			com.fasterxml.jackson.core
			jackson-databind
			2.8.6
		

		
			com.fasterxml.jackson.dataformat
			jackson-dataformat-csv
			2.8.6
		

局限是Object字段无法序列化,需要自定义序列规则。

转载于:https://my.oschina.net/slightScenery/blog/3084293

你可能感兴趣的:(CSV example)