C# 填充列数 return 值 1

C# Number of filled column return value 1

我知道有几种方法可以根据个人要求查找填充的行数和列数。我尝试使用 Cells.Find 方法来查找填充的行数和列数的方法之一。我在这里找到了一个相关的 post:,这正是我所需要的。我复制了格式并替换了变量并且工作正常。但是,lastUsedColumn 的 return 值是 1 而不是 4,而 lastUsedRow return 5 是完全正确的。我的 Excel 文件的文件格式是 .xls 而不是 .csv。我已经通过阅读在线文档学习 C# 一段时间了,但仍然不明白为什么 xlByColumns 在这里不起作用,或者我遗漏了什么..?谁能帮忙解释一下。。谢谢

我的 Excel(.xls)

中的数据示例
0.02 | 1.352 | 2.447 | -3.9924

0.04 | 2.991 | 9.556 | 3.227

0.06 | -9.119 | 1.883 | 2.004

0.08 | 5.382 | -9.003 | 7.441

1.00 | -8.803 | - 6.443 | 7.210

*符号 |代表列,所以一共4列,一共5行。

Excel.Application app = null; 
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
double lastUsedRow = 0;
double lastUsedColumn = 0;

string FFile = @"C:\Users\Student\Downloads\FFile.xls"; 
StreamWriter rowvalue = File.CreateText(@"C:\Users\Student\Downloads\rowvalue.xls"); 
StreamWriter colvalue = File.CreateText(@"C:\Users\Student\Downloads\colvalue.xls"); 

app = new Excel.Application();
app.Visible = false;
wb = app.Workbooks.Open(FFile, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

ws = (Excel.Worksheet)wb.Worksheets[1];

object missV = System.Reflection.Missing.Value;

// Find the last real row
// Return result 5 (correct)
lastUsedRow = ws.Cells.Find("*", missV, missV, missV, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, true, missV).Row;

rowvalue.WriteLine(lastUsedRow);

// Find the last real column
// Return result 1 (wrong)
lastUsedColumn = ws.Cells.Find("*", missV, missV, missV, Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlPrevious, false, true, missV).Column;

colvalue.WriteLine(lastUsedColumn);

您正在将文本文件导入 Excel,而 Excel 无法识别分隔符。从而将数据从一行读入一列。这些行被转换为一行,所以这就是为什么你得到正确的行数。

查看您的 .xls 文件(使用记事本)并查看使用的分隔符。将 Open 调用中的 5 替换为正确的数字 as described in the documentation

Value Delimiter
1 Tabs
2 Commas
3 Spaces
4 Semicolons
5 Nothing
6 Custom character (see the Delimiter argument)