VB.NET - 读取 Excel 文件的全部内容
我已经知道如何使用 VB.NET 读取 .xls 文件的特定单元格的基本过程,但我不知道如何自动从此类文件中获取所有数据。
基本上,我获取的数据是这样的:
Dim xlApp As Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
xlApp = New Excel.Application
wb = xlApp.Workbooks.Open("myfile.xls")
ws = wb.Worksheets("worksheet1")
For Each cell In ws.Range("A1", "C10")
Console.WriteLine(cell.value)
Next
在这种情况下,我知道 A、B 和 C 列的前 10 行中会有内容,但是如果我有一个大小如此巨大的文档,我该怎么办内容甚至可能会不时发生变化?我知道还有一个属性 ws.rows.count 但它总是返回一个像 60000 这样的大值,即使只有几行被占用。
所以基本上,我正在寻找一种简单的方法来循环遍历 Excel 文件的所有已使用的行,并可以访问该行中的每个单元格。
I already know the basic procedure of how to read specific cells of an .xls file using VB.NET but I can't figure out how to automatically get all the data from such a file.
Basically, I'm obtaining the data like this:
Dim xlApp As Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
xlApp = New Excel.Application
wb = xlApp.Workbooks.Open("myfile.xls")
ws = wb.Worksheets("worksheet1")
For Each cell In ws.Range("A1", "C10")
Console.WriteLine(cell.value)
Next
In this case, I know that there will be content in the first 10 rows of the columns A, B and C but what would I have to do if I had a huge document whose size and content might even change from time to time? I know that there is also an attribute ws.rows.count but this always returns a big value like 60000 even if only a few rows are occupied.
So basically, I'm looking for a simple way to loop through all the used rows of an Excel file with the possibility of accessing each cell in that row.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 VBA 中 - 与 VB.NEt 不同(所以我在这里可能偏离目标),您可以使用
(根据需要“重置”UsedRange 的第一行,
SpecialCells(xlCellTypeLastCell)
通常会给出比实际存在的范围更大),或更常见或
in VBA - as distinct from VB.NEt (so I may be off target here) you would either use
(the first line as needed to "reset" the UsedRange,
SpecialCells(xlCellTypeLastCell)
will often give a larger range than is actually present), or more commonlyor
仍然在 VBA 中,我们经常使用
End
语句来解决此类问题:更改列名称或编号以满足您的需要(或者以与最后一行相同的方式使用
End 查找它) (xl左)
Still in VBA, we often use the
End
statement for this kind of issue:Change the column name or number to fit your needs (or find it in the same way as the last row with
End(xlLeft)
这是我过去使用过的一个例子。
Here's an example that I have used in the past.
Dim aDataTemp = xl.Worksheets(sSheetName).UsedRange.value
Dim aDataTemp = xl.Worksheets(sSheetName).UsedRange.value
使用 Spire.XLS 可以轻松读取所有可用单元格,例如:
It is easy to use Spire.XLS to read all available cells, for example: