C#填充的列返回值1

问题描述 投票:-1回答:1

我知道有几种方法可以根据个人需求找到行和列的总数。我尝试使用Cells.Find方法之一来查找已填充的行和列的数量。我在这里找到了一个相关的帖子:C# Excel : Correct way to get Rows and Columns count,这正是我所需要的。我复制了格式并替换了变量,并且工作正常。但是,lastUsedColumn的返回值是1而不是4,而lastUsedRow返回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);
c# excel xls
1个回答
0
投票

您正在将文本文件导入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)
© www.soinside.com 2019 - 2024. All rights reserved.