簡體   English   中英

無法從 Excel 單元格讀取文本?

[英]Cannot read text from Excel cell?

我試圖獲取輸入到 Excel 工作表中特定單元格的字符串值。 我的代碼如下:

Excel.Application excel_app = new Excel.Application();
Excel.Workbook dashboard = excel_app.Workbooks.Open(Filename:@"H:\charge_code_project\test_dashboard.xlsb", ReadOnly: true);
Excel.Worksheet worksheet = (Excel.Worksheet)dashboard.Worksheets[package_type];
Excel.Range range = worksheet.UsedRange;
int rowCount = range.Rows.Count;
string cell_text = worksheet.Cells[10, 10].Text;

當我嘗試構建時,我在最后一行收到以下錯誤:

Error   CS1061  'object' does not contain a definition for 'Text' and no accessible extension method 'Text' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

我在以前的項目中使用過這種從 excel 文件中讀取文本的方法並且它有效,所以我知道 .Text 存在。 我認為我以前使用它的方式和我現在使用它的方式沒有區別。 我相信我已經包含了所有必要的程序集引用和 using 語句:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Windows.Forms.VisualStyles;
using System.IO;

我添加了以下程序集引用:

Microsoft Excel 16.0 Object Library
Microsoft Office 15.0 Object Library 
Microsoft Office 16.0 Object Library
Microsoft Visual Basic for Applications Extensibility 5.3
OLE Automation

有人能幫我看看我做錯了什么嗎?

您收到異常,因為Range對象沒有 Text 屬性。

您應該使用Value屬性來獲取單元格/范圍的值。

示例代碼:

string cell_text = ((Range)worksheet.Cells[10, 10]).Value.ToString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM