gpt4 book ai didi

java - 有没有一种简单的方法来输出按列的 CSV?

转载 作者:搜寻专家 更新时间:2023-11-01 01:57:46 24 4
gpt4 key购买 nike

我正在尝试将多个不同长度的数据列表输出到 CSV 文件。每个列表应该是输出 CSV 文件中的一列。有没有直接的做事方式?如果我将每个列表作为一行输出,我将循环遍历每个列表并在到达末尾时输出一个返回值,但这种方法在按列工作时不起作用。

我曾想一次检查所有列表,逐项检查并递增计数器,但这也会失败,因为有些列表比其他列表长。为了解决这个问题,我必须在每次迭代时检查计数器是否超过了每个列表的末尾,这在计算方面会相当昂贵。

感谢任何想法!

最佳答案

我认为这很简单:

public static void main(String... args) throws IOException {

ArrayList<ArrayList<String>> rows = getRandomData();

if (rows.size() == 0)
throw new RuntimeException("No rows");

// normalize data
int longest = 0;
for (List<String> row : rows)
if (row.size() > longest)
longest = row.size();

for (List<String> row : rows)
while (row.size() < longest)
row.add("");

if (longest == 0)
throw new RuntimeException("No colums");

// fix special characters
for (int i = 0; i < rows.size(); i++)
for (int j = 0; j < rows.get(i).size(); j++)
rows.get(i).set(j, fixSpecial(rows.get(i).get(j)));

// get the maximum size of one column
int[] maxColumn = new int[rows.get(0).size()];

for (int i = 0; i < rows.size(); i++)
for (int j = 0; j < rows.get(i).size(); j++)
if (maxColumn[j] < rows.get(i).get(j).length())
maxColumn[j] = rows.get(i).get(j).length();

// create the format string
String outFormat = "";
for (int max : maxColumn)
outFormat += "%-" + (max + 1) + "s, ";
outFormat = outFormat.substring(0, outFormat.length() - 2) + "\n";

// print the data
for (List<String> row : rows)
System.out.printf(outFormat, row.toArray());

}

private static String fixSpecial(String s) {

s = s.replaceAll("(\")", "$1$1");

if (s.contains("\n") || s.contains(",") || s.contains("\"") ||
s.trim().length() < s.length()) {
s = "\"" + s + "\"";
}

return s;
}

private static ArrayList<ArrayList<String>> getRandomData() {

ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();

String[] rand = { "Do", "Re", "Song", "David", "Test", "4", "Hohjoh", "a \"h\" o", "tjo,ad" };
Random r = new Random(5);

for (int i = 0; i < 10; i++) {

ArrayList<String> row = new ArrayList<String>();

for (int j = 0; j < r.nextInt(10); j++)
row.add(rand[r.nextInt(rand.length)]);

data.add(row);
}

return data;
}

输出(非常难看,因为它是随机的)(escapes):

Re       , 4           , "tjo,ad" , "tjo,ad" ,    
"tjo,ad" , "a ""h"" o" , , ,
Re , "a ""h"" o" , Hohjoh , "tjo,ad" , 4
4 , David , , ,
4 , Test , "tjo,ad" , Hohjoh , Re
Do , Hohjoh , Test , ,
Hohjoh , Song , , ,
4 , Song , , ,
4 , Do , Song , Do ,
Song , Test , Test , ,

关于java - 有没有一种简单的方法来输出按列的 CSV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4338521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com