在 Apache Camel 中输出 CSV 列 headers

Output CSV column headers in Apache Camel

是否可以在本页的 "Marshalling a Map to CSV" 示例中输出 header 行? http://camel.apache.org/csv.html

Map<String, Object> body = new LinkedHashMap<>();
body.put("foo", "abc");
body.put("bar", 123);

from("direct:start")
.marshal().csv()
.to("mock:result");

输出:

abc,123

期望的输出:

foo,bar
abc,123

您需要使用支持配置headers的Camel 2.15以上版本。请参阅文档:http://camel.apache.org/csv.html

camel-csv 的单元测试有一些例子 https://github.com/apache/camel/tree/master/components/camel-csv

我定义了 List<Map<String,String>> 的聚合器,它在第一次调用时将 Map.get(0).keySet() 添加为聚合 List 的元素 0(例如 oldExchange==null)。聚合完成后,我对结果调用了 marshal().csv()

使用springxml

Using spring xml

      <multicast stopOnException="true">
    <pipeline>
      <log message="saving table ${headers.tablename} header to ${headers.CamelFileName}..."/>
      <setBody>     
<groovy>request.headers.get('CamelJdbcColumnNames').join(";") + "\n"</groovy>
      </setBody>
      <to uri="file:output"/>
    </pipeline>

    <pipeline>
      <log message="saving table ${headers.tablename} rows to ${headers.CamelFileName}..."/>
      <marshal>
        <csv delimiter=";" headerDisabled="false" useMaps="true"/>
      </marshal>
      <to uri="file:output?fileExist=Append"/>
    </pipeline>
  </multicast>

http://www.redaelli.org/matteo-blog/2019/05/24/exporting-database-tables-to-csv-files-with-apache-camel/

再见马泰奥