VB.net:如何将数据从 Excel 工作表获取到字符串对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1223515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:19:34  来源:igfitidea点击:

VB.net: How to get data from Excel worksheet to string object?

vb.netexcelexcel-2007

提问by Anton

I've tried this:

我试过这个:

    'start Excel app
    Dim exApp As Microsoft.Office.Interop.Excel.Application
    exApp = CreateObject("Excel.Application")

    ' load excel document
    exApp.Workbooks.Open(fname)
    Dim exSheet As Microsoft.Office.Interop.Excel.Worksheet
    exSheet = exApp.Workbooks(1).Worksheets(1)

and than, for example accessing "C3" cell:

然后,例如访问“C3”单元格:

 Dim b As String
 b = exSheet.Cells("A3")

or:

或者:

b = exSheet.Cells(3,3)

and it throws me an exception. I'm feeling that I'm doing something wrong with the object access, but this method worked in embedded VB, and do not works in .net. Also, tried to google the exception code, with no relevant result.

它给我一个例外。我觉得我在对象访问方面做错了,但是这种方法在嵌入式 VB 中有效,而在 .net 中无效。此外,试图用谷歌搜索异常代码,但没有相关结果。

回答by Mark

Try:

尝试:

b = exSheet.Range("A3").Value.ToString

回答by shahkalpesh

I don't think you should write code in VB6 style for vb.net.

我认为您不应该为 vb.net 编写 VB6 风格的代码。

Looking at the code example, I think what you need is

查看代码示例,我认为您需要的是

b = exSheet.Cells(3,3).Text

or

或者

b = exSheet.Cells(3,3).Value

EDIT: I guess it the reference should be assigned to an instance of range.
So, the code might look like

编辑:我想应该将引用分配给范围的实例。
所以,代码可能看起来像

Range exampleRange = exSheet.Cells(3,3)
b = exampleRange.Text 'OR it can be b = exampleRange.Value