【问题标题】:clear Carriage Return from CSV file Java从 CSV 文件 Java 清除回车
【发布时间】:2012-04-26 15:29:48
【问题描述】:

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

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

【问题讨论】:

  • 您是否查看了您要操作的文件的十六进制转储?然后您可能能够找到换行符(例如 chr(10) 和/或 chr(13))

标签: java excel csv return


【解决方案1】:

你可以试试

System.getProperty("line.separator")

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

【讨论】:

    【解决方案2】:

    重申您的问题:您有一个 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 格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多