[英]Export Java code to CSV and import in Excel 2013
I export Java source code to a CSV file. 我将Java源代码导出到CSV文件。 Because Java code can contain a lot of normal separators, I used ´ as separator (is there a better one for Java?). 因为Java代码可以包含许多普通的分隔符,所以我使用´作为分隔符(Java是否有更好的分隔符?)。
One of my exported data rows looks like this in the output file: 我的导出数据行之一在输出文件中如下所示:
2.0´"if (x < 1) {
System.out.println(x + x);
if (x < 2) {
System.out.println("xy");
}
}"
But when I import this into excel, what happens is that the first System.out until the end of the actual row ( "
) will land in the second row. I also tried omitting the "
in the second column. 但是,当我将其导入excel时,会发生的情况是第一个System.out直到实际行( "
)的末尾将进入第二行。我还尝试在第二列中省略"
。
The String generated by Java for the second column is Java为第二列生成的字符串是
condStr = ((IfStatement) cond.getOriginalNode()).toString();
I think this is a problem of Excel, as my CSV file looks fine. 我认为这是Excel的问题,因为我的CSV文件看起来不错。 What can I change to make it be imported properly in Excel (2013)? 我如何更改才能将其正确导入Excel(2013)?
You need \\r\\n
at each end of line in the CSV file. 在CSV文件的每一行末尾都需要\\r\\n
。 Quotes inside the text should be escaped with double quotes. 文本内的引号应使用双引号转义。 If you choose the semicolon as field separator, you can open the file directly with Excel (file extension *.csv
should be bound to Excel). 如果选择分号作为字段分隔符,则可以直接使用Excel打开文件(文件扩展名*.csv
应该绑定到Excel)。
Here is a small example: 这是一个小例子:
import java.io.IOException;
public class CsvTest {
/**
* CSV quote
*
* @param fieldContent String to quote
* @param sep Field separator
* @param quote Text quote character
* @param target Target (e.g. StringBuilder or Writer)
* @throws IOException
*/
private static void quote(CharSequence fieldContent, char sep, char quote, Appendable target) throws IOException {
target.append(quote);
// Escape the quoting character.
final int len = fieldContent.length();
for(int i = 0; i < len; i++) {
final char c = fieldContent.charAt(i);
if(c == quote) {
target.append(quote).append(quote);
} else {
target.append(c);
}
}
target.append(quote);
}
public static void main(String[] args) throws IOException {
final char sep = ';';
final char quote = '"';
final StringBuilder sb = new StringBuilder();
quote("2.0", sep, quote, sb);
sb.append(sep);
quote("if (x < 1) {\r\n" +
" System.out.println(x + x);\r\n" +
" if (x < 2) {\r\n" +
" System.out.println(\"xy\");\r\n" +
" }\r\n" +
"}", sep, quote, sb);
System.out.println(sb.toString());
}
}
Resulting in 导致
"2.0";"if (x < 1) {
System.out.println(x + x);
if (x < 2) {
System.out.println(""xy"");
}
}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.