1

对于我的问题,我已经看到了很多答案。我已经尝试了所有这些,但没有一个对我有用。当我导出我的 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", "");

如您所见,我尝试了几种不同的删除回车的方法,但均未成功。谁能告诉我我做错了什么?

4

2 回答 2

0

To restate your question: You have an Excel document with cells that contains new lines. You want to export this document to CSV and the new lines within the cells are corrupting the CSV file.

Removing Newlines

It appears that you have tried removing the new lines from each cell as they are written to CSV, but state that it does not appear to work. In the code that you give you replace just the \r characters, but not the \n characters. I would try this:

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

which will replace all both types of characters that could be interpreted as newlines (indeed on Windows, a newline is usually two characters together \r\n).

As far as your regular expressions for removing newlines go here is the rundown:

",,"  // 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.

Writing Escaped Newlines

It should be possible to generate CSV files that include newlines within the cells. Indeed Excel itself can do this. There is an ExcelCSVPrinter java library here that will do all the escaping you need for you: http://ostermiller.org/utils/CSV.html

This is a single line of excel format csv:

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

http://ostermiller.org/utils/CSV.html also provides an ExcelCSVParser Java library for reading Excel CSV format like that.

于 2012-11-30T20:16:09.743 回答
0

你可以试试

System.getProperty("line.separator")

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

于 2012-04-26T15:33:15.857 回答