如何将两个ArrayLists打印到具有多列的csv文件中?

编程入门 行业动态 更新时间:2024-10-25 21:27:10
本文介绍了如何将两个ArrayLists打印到具有多列的csv文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个数组列表,如下所示,

I have two array lists like shown below,

import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.*; class Reader { public static void main(String args[]) throws FileNotFoundException { ArrayList<String> animal = new ArrayList<>(); animal.add("Dog"); animal.add("Cat"); animal.add("Mouse"); ArrayList<Integer> numbers = new ArrayList<>(); for (int i = 1; i <= 15; i++) { numbers.add(i); } PrintWriter writer = new PrintWriter("animals.csv"); for (String ani : animal) { writer.println(ani + ","); } writer.close(); } }

我希望.csv文件中的输出像这样.

I want the output to be like this in the .csv file.

Dog,1,2,3,4,5, Cat,6,7,8,9,10, Mouse,11,12,13,14,15,

当我使用for循环时,在.csv文件中,数组列表的输出将一个显示在另一个下方.

When I use for-loops, the output of the array lists gets printed one below the other in the .csv file.

如何格式化所需的数组列表,使其在Excel中看起来像这样?

How do I format the array lists the way I desired, so it looks like this in Excel?

推荐答案

使用writer.print()代替writer.println()

在您使用的方法名称中注意'ln',表示打印行.

Notice 'ln' in the method name you are using, which means print line.

更新:要同时添加数字和动物:

Update: To also add numbers along with animal:

public static void main(final String[] args) throws FileNotFoundException { ArrayList<String> animal = new ArrayList<>(); animal.add("Dog"); animal.add("Cat"); animal.add("Mouse"); ArrayList<Integer> numbers = new ArrayList<>(); for (int i = 1; i <= 15; i++) { numbers.add(i); } PrintWriter writer = new PrintWriter("animals.csv"); List<String> row = new ArrayList<>(); int i = 0; for (String ani : animal) { row.add(ani); for (int j = 0; j < 5; j++) { row.add(String.valueOf(numbers.get(i++))); } writer.println(String.join(",", row)); row.clear(); } writer.close(); }

更多推荐

如何将两个ArrayLists打印到具有多列的csv文件中?

本文发布于:2023-05-27 23:10:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/306087.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有多   如何将   两个   文件   ArrayLists

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!