简体   繁体   中英

Cannot read text from Excel cell?

I am trying to grab the string value entered into a specific cell in an excel worksheet. My code is below:

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;

I receive the following error on the last line when I try to build:

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?)

I have used this method of reading text from an excel file in previous projects and it has worked, so I know that .Text exists. I see no difference between how I used it previously and how I am using it currently. I believe I have included all the necessary assembly references and using statements:

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;

I have added the following assembly references:

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

Would anyone help me see what I am doing wrong?

You are getting the exception since the Range object does not have the Text property.

You should use the Value property to get the value of the cell/range.

Sample code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM