c# - 如何删除excel中每个单元格的回车?

标签 c# excel cell

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

 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 单元格中更改回车吗?

最佳答案

如果在 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);
}

关于c# - 如何删除excel中每个单元格的回车?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27889664/

相关文章:

c# - C#-BlockingCollection : Can we have 2 threads Take() the same value?

Excel:计算日期单元格列中特定月份的频率

vba - 两个日期之间的月数

swift - Swift 3 中 UITableView 中未知的行数

ios - 如何在 UITableViewCellStyleSubtitle 中显示多行

dom - 在Dart中查询表格中的单元格

c# - 为什么短原语有赋值运算符(&=、+=)但没有非赋值运算符(&、+)?

c# - 当 Item 改变时通知 ObservableCollection

c# - 如何在 WP8 应用程序中使用媒体查看器

c# - 在 Excel 中执行拖放操作时 DragDrop.DoDragDrop 不返回