我试图使用openCSV
java库在csv文件中写入一些公式数据,但它只在每个单元格中写入了大约90%的字符串。是否有任何已知的问题可能导致这种行为?
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
FileOutputStream fosW = new FileOutputStream("C:\Users\Desktop\formula.csv");
OutputStreamWriter osw = new OutputStreamWriter(fosW, "UTF-8");
CSVWriter writerCSW = new CSVWriter(osw);
int k = 0;
String[] b = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT"};
String[] line = new String[100];
for (int i = 0; i < b.length - 1; i++) {
String a = "=IF(legend!" + b[i] + "$3='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1] + "$3,IF(legend!" + b[i] + "$4='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1] + "$4,IF(legend!" + b[i] + "$5='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1] + "$5,IF(legend!" + b[i] + "$6='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1] + "$6,IF(legend!" + b[i] + "$7='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1] + "$7,IF(legend!" + b[i] + "$8='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1] + "$8,#error#))))))";
System.out.println(a);
line[k] = a;
k++;
}
writerCSW.writeNext(line);
}
我认为您的问题是您错误地使用了库。(尽管这可能是我的误解。
你的B长46。您的CSV文件将有45个条目。
线[k]正好是1行。我想你假设行数组中的每个索引都是。这是错误数字1(可能)。
但是,文件没有完全填充的原因是您没有关闭流,因此一旦程序存在,数据就会丢失。所以你会想要关闭你的编写器,或者更好的是,使用"尝试资源"块。我已经重写了你的代码来做到这一点:
public static void main(String[] args) throws IOException {
FileOutputStream fosW = new FileOutputStream("/home/artur/tmp/test.csv");
OutputStreamWriter osw = new OutputStreamWriter(fosW, "UTF-8");
try (CSVWriter writerCSW = new CSVWriter(osw)) {
String[] b = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ",
"AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT" };
System.out.println(b.length);
for (int i = 0; i < b.length - 1; i++) {
String a = "=IF(legend!" + b[i] + "$3='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1]
+ "$3,IF(legend!" + b[i] + "$4='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1]
+ "$4,IF(legend!" + b[i] + "$5='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1]
+ "$5,IF(legend!" + b[i] + "$6='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1]
+ "$6,IF(legend!" + b[i] + "$7='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1]
+ "$7,IF(legend!" + b[i] + "$8='Form responses 1'!" + b[i + 1] + "2,legend!" + b[i + 1]
+ "$8,#error#))))))";
String[] line = a.split(",");
writerCSW.writeNext(line);
System.out.println(i);
}
}
}
注意,我已经改变了一些事情,所以它可能不会完全按照你的意愿。但是,您应该能够从这个例子中看出哪里出了问题。
请注意:看看我是如何用逗号分隔字符串a的?这是为了为CSV输入生成一个数组。它将自动为您插入您选择的分隔符。如果您不想这样做,请去掉CSVWriter,并使用普通的Filewriter。您可以通过构造字符串手动生成CSV行。当使用OpenCSV时,这是不必要的。
我希望这会有所帮助,
Artur