清除CSV文件中的回车Java

我已经看到了许多我对这个问题的答案。 我已经尝试了所有这些,他们都没有为我工作。 当我导出我的excel文件时,如果有回车符,它将进入下一列的数据input新行。

我试图删除列级回车,如下所示:

String col = columnName.replaceAll("\r", ""); reportColumn.put( "column", col ); 

这遍历每个块并填充Excel表单。 此外,我试图删除回车这里包含整个csv文件的string:

 String csv = ""; CSVReportGenerator generator = new CSVReportGenerator( ); generator.setReportColumns( this.reportColumns ); generator.setReportRows( rows ); generator.setApplicationPath(""); generator.setNL('\n'); generator.setDebuggingON(Config.DEBUGGING_ON); generator.produceReport( ); csv = generator.getCSV( ); csv.replaceAll(",,", ""); csv.replaceAll(".", ""); csv.replaceAll("\r", ""); csv.replaceAll("\n", ""); csv.replaceAll("\r\n", ""); csv.replaceAll("\\r\\n", ""); 

正如你可以看到我已经尝试了几个不同的方法来删除回车。 有谁可以告诉我我做错了什么?

你可以试试

System.getProperty("line.separator")

这样做的一个优点是它独立于平台。

重申您的问题:您有一个包含新行的单元格的Excel文档。 您希望将此文档导出为CSV,并且单元格内的新行损坏了CSV文件。

删除换行符

看起来你已经尝试从每个单元格中删除新的行,因为它们被写入CSV,但表明它似乎没有工作。 在您给出的代码中,只replace\ r字符,而不是\ n字符。 我会试试这个:

 String col = columnName.replaceAll("[\r\n]", ""); reportColumn.put( "column", col ); 

这将replace所有可以被解释为换行符的两种types的字符(事实上,在Windows上,换行符通常是两个字符\ r \ n)。

至于去除换行符的正则expression式在这里是破败的:

 ",," // Removes two commas, not newlines "." // Removes all characters, except newlines "\r" // Removes the "carriage return" characters (half of the Windows newline) "\n" // Removes the "new line" characters (half of the Windows newline) "\r\n" // Removes a Windows newline but not individual newline characters "\\r\\n" // Same as "\r\n" but the escapes are handled by the regex library rather than the java compiler. "[\r\n]" // Should remove any newline character. "[\\r\\n]" // Same as above but with extra escaping. 

写出逃脱的换行符

应该可以在单元格内生成包含换行符的CSV文件。 确实Excel本身可以做到这一点。 这里有一个ExcelCSVPrinter java库,可以完成所有你需要的转义: http : //ostermiller.org/utils/CSV.html

这是一个excel格式csv单行:

 "cell one","first line of cell two second line of cell two","cell three" 

http://ostermiller.org/utils/CSV.html还提供ExcelCSVParser Java库,用于读取Excel CSV格式的文件。