将Java代码导出到CSV并在Excel 2013中导入

我将Java源代码导出到CSV文件。 因为Java代码可以包含很多正常的分隔符,所以我使用了“作为分隔符(对于Java有更好的分隔符)吗?

其中一个导出的数据行在输出文件中看起来像这样:

2.0´"if (x < 1) { System.out.println(x + x); if (x < 2) { System.out.println("xy"); } }" 

但是当我把它导入到excel中的时候,第一个System.out直到实际行( " )的末尾会落在第二行,我也试着省略了"在第二列。

Java为第二列生成的string是

 condStr = ((IfStatement) cond.getOriginalNode()).toString(); 

我认为这是一个Excel的问题,因为我的CSV文件看起来不错。 我可以更改哪些内容以便在Excel(2013)中正确导入?

您需要在CSV文件的每行末尾添加\r\n 。 文本中的引号应该用双引号括起来。 如果select分号作为字段分隔符,则可以直接使用Excel打开文件(应将文件扩展名*.csv绑定到Excel)。

这是一个小例子:

 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 (eg 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()); } } 

导致

 "2.0";"if (x < 1) { System.out.println(x + x); if (x < 2) { System.out.println(""xy""); } }"