从文本字段中删除CR / LF

时间:2013-05-23 17:08:33

标签: c# excel-interop

我遇到问题,当我从列中检索txt文件时,使用:

scanObject = scanWorksheet.Cells[i, scanCols[j]]; 

scanRange = (Excel.Range)scanObject;

scanRangeValue = scanRange.Value2;

它传递换行,LF,命令。从那里我生成一个文本文件,用作另一个程序的输入,但是这个LF命令使导入系统跳过该字段。如何在检索文本列时删除它们?

1 个答案:

答案 0 :(得分:0)

在步骤中,您可以看到每个人做了什么:

// get the value in the cell (which is an object from Value2)
object scanRangeValue = scanRange.Value2;
// cast to string (you may need to check for errors if it is not a string)
string scanStringValue = (string)scanRangeValue;
// Replace both \r\n and \r and \n
scanStringValue = scanStringValue.Replace("\r", "").Replace("\n", "");

注意Value2是一种对象类型,因此您需要转换为string。如果返回的值不是string,则可能会抛出异常,因此您可能需要使用try ... catch ...或其他测试,例如if (scanRangeValue is string)(请参阅MSDN - How to: Safely Cast by Using as and is Operators (C# Programming Guide)