如何删除excel中每个单元格中的回车return?

How to delete carriage return in every cell in excel?

我使用此代码从 excel 中的每个单元格中删除回车符 return:

 Microsoft.Office.Interop.Excel.Range cells = reportSheet.Cells;
 cells.Replace("\n", "",
               Microsoft.Office.Interop.Excel.XlLookAt.xlWhole,
               Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, false,
               false, true, false);

我收到一条消息:

"Microsoft Office Excel cannot find any data to replace. Check if your search formatting and criteria are defined correctly. If you are sure that matching data exists in this workbook, it may be on a protected sheet. Excel cannot replace data on a protected worksheet."

有人知道如何在 excel 单元格中更改回车 return 吗?

如果在 Excel 中输入数据并按下 Alt+Enter 键,它会插入一个换行符。但是,如果将输入作为 Windows 换行符 (CR+LF) 写入单元格,它将以完全相同的方式显示在 Excel 中。

确保替换所有换行符的最安全方法是循环遍历所有可能性并替换每个:

Microsoft.Office.Interop.Excel.Range cells = reportSheet.Cells;
// Cycle through each newline code and replace.
foreach (var newline in new string[] { "\r\n", "\r", "\n" })
{
    cells.Replace(newline, "",
                  Microsoft.Office.Interop.Excel.XlLookAt.xlPart, // Use xlPart instead of xlWhole.
                  Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, false,
                  false, true, false);
}