[英]Extra carriage return added while generating txt file from bean objects in java using open CSV Writer
[英]clear Carriage Return from CSV file Java
我已经看到许多关于这个问题的答案。 我已经尝试了所有这些方法,但没有一个对我有用。 当我导出excel文件时,如果有回车符,它将输入数据,该数据应继续到下一列进入新行。
我正在尝试删除列级的回车符,如下所示:
String col = columnName.replaceAll("\r", "");
reportColumn.put( "column", col );
这将遍历每个块并填充excel工作表。 另外,我正在尝试使用包含整个csv文件的字符串在此处删除回车符:
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,但指出它似乎不起作用。 在您提供的代码中,仅替换\\ r字符,而不替换\\ n字符。 我会尝试这样的:
String col = columnName.replaceAll("[\r\n]", "");
reportColumn.put( "column", col );
它将替换可能解释为换行符的所有两种类型的字符(实际上,在Windows中,换行符通常是两个字符加在一起\\ r \\ n)。
至于删除换行符的正则表达式,请参见以下摘要:
",," // 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格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.