mirror of
https://gitee.com/dromara/hutool.git
synced 2025-04-05 17:37:59 +08:00
!1222 CsvWriter 重载 writeBeans 方法
Merge pull request !1222 from nickname/v5-master
This commit is contained in:
commit
cba4a832eb
@ -252,6 +252,30 @@ public final class CsvWriter implements Closeable, Flushable, Serializable {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将一个Bean集合写出到Writer,并自动生成表头
|
||||
*
|
||||
* @param beans Bean集合
|
||||
* @param properties Bean 中指定的可以导出的属性
|
||||
* @return this
|
||||
*/
|
||||
public CsvWriter writeBeans(Iterable<?> beans, String... properties) {
|
||||
if (CollUtil.isNotEmpty(beans)) {
|
||||
boolean isFirst = true;
|
||||
Map<String, Object> map;
|
||||
for (Object bean : beans) {
|
||||
map = BeanUtil.beanToMap(bean, properties);
|
||||
if (isFirst) {
|
||||
writeHeaderLine(map.keySet().toArray(new String[0]));
|
||||
isFirst = false;
|
||||
}
|
||||
writeLine(Convert.toStrArray(map.values()));
|
||||
}
|
||||
flush();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写出一行头部行,支持标题别名
|
||||
*
|
||||
|
@ -136,6 +136,41 @@ public class CsvUtilTest {
|
||||
writer.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void writeBeansWithPropertiesTest() {
|
||||
|
||||
@Data
|
||||
class Student {
|
||||
Integer id;
|
||||
String name;
|
||||
Integer age;
|
||||
}
|
||||
|
||||
String path = FileUtil.isWindows() ? "d:/test/testWriteBeans.csv" : "~/tmp/testWriteBeans.csv";
|
||||
CsvWriter writer = CsvUtil.getWriter(path, CharsetUtil.CHARSET_UTF_8);
|
||||
List<Student> students = new ArrayList<>();
|
||||
Student student1 = new Student();
|
||||
student1.setId(1);
|
||||
student1.setName("张三");
|
||||
student1.setAge(18);
|
||||
|
||||
Student student2 = new Student();
|
||||
student2.setId(2);
|
||||
student2.setName("李四");
|
||||
student2.setAge(22);
|
||||
|
||||
Student student3 = new Student();
|
||||
student3.setId(3);
|
||||
student3.setName("王五");
|
||||
student3.setAge(31);
|
||||
|
||||
students.add(student1);
|
||||
students.add(student2);
|
||||
students.add(student3);
|
||||
writer.writeBeans(students,"name","age");
|
||||
writer.close();
|
||||
}
|
||||
@Test
|
||||
@Ignore
|
||||
public void readLfTest(){
|
||||
|
Loading…
Reference in New Issue
Block a user