本文介绍了如何将两个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文件中?
发布评论