我正嘗試使用BeanIO框架將數據列表寫入CSV文件。我能夠將單個對象寫入CSV,但無法寫入數據列表。使用BeanIO將CSV文件寫入CSV文件
我曾嘗試下面的代碼:
package com.beanio.example;
import java.util.Date;
public class Employee {
String firstName;
String lastName;
String title;
int salary;
Date hireDate;
// setters and getters follow ...
}
<beanio xmlns="http://www.beanio.org/2012/03"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.beanio.org/2012/03 http://www.beanio.org/2012/03/mapping.xsd">
<stream name="employeeFile" format="csv">
<record name="header" class="com.beanio.example.GroupH" order="1" occurs="1">
<field name="h1" default="Header1" ignore="true" />
<field name="h2" default="Header2" ignore="true" />
<field name="h3" default="Header2" ignore="true" />
</record>
<record name="employee" class="com.beanio.example.Employee" order="2">
<field name="firstName" />
<field name="lastName" />
<field name="title" />
<field name="salary" />
<field name="hireDate" format="MMddyyyy" />
</record>
</stream>
</beanio>
public class Main {
public static void main(String[] args) throws Exception {
// create a StreamFactory
StreamFactory factory = StreamFactory.newInstance();
// load the mapping file
factory.loadResource("mapping.xml");
List<Employee> employees = new ArrayList<Employee>();
Employee employee = new Employee();
employee.setFirstName("Jennifer");
employee.setLastName("Jones");
employee.setTitle("Marketing");
employee.setSalary(60000);
employee.setHireDate(new Date());
Employee employee1 = new Employee();
employee1.setFirstName("JACk");
employee1.setLastName("Jones");
employee1.setTitle("Tele");
employee1.setSalary(60000);
employee1.setHireDate(new Date());
employees.add(employee);
employees.add(employee1);
// use a StreamFactory to create a BeanWriter
BeanWriter out = factory.createWriter("employeeFile", new File("employee.csv"));
// write an Employee object directly to the BeanWriter
out.write(employees);
out.flush();
out.close();
}
}
我期待在CSV結果按照以下格式:
FirstName,LastName,Title,Salary,HireDate
例如:
Jennifer,Jones,Marketing,60000,24-12-2016
JACK,Jones,TELE,60000,24-12-2016
有人可以幫我嗎?