I wrote a little C# program that opens up an Excel workbook and a worksheet and iterates over all the cells in a worksheet and prints out the value in each cell.
The problem I am having is the console is printing System.Object[,]
instead of the actual cell values, it seems as it is an infinite loop.
Does anyone know why it is not printing the actual values?
Here is my program:
using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using NetOffice.ExcelApi;
using NetOffice.ExcelApi.Enums;
using Excel = NetOffice.ExcelApi.Application;
namespace excelApp
{
class Program
{
Excel excelApplication;
Workbook workbook;
Worksheet sheet;
[STAThreadAttribute]
public static void Main(string[] args)
{
Program p = new Program();
p.openWorkSheet(@"C:\Users\HP\Desktop\Book1.xlsx", 2);
p.printValues();
Console.ReadKey(true);
}
private void openWorkSheet(string path, int worksheet)
{
excelApplication = new Excel
{
Visible = true,
ScreenUpdating = true
};
try
{
workbook = excelApplication.Workbooks.Open(path);
sheet = (Worksheet)workbook.Worksheets[worksheet];
}
catch
{
Console.WriteLine("File does not exist");
}
}
private void printValues()
{
Range range = sheet.Cells[2, 2];
Range rngLastCell = range.get_End(XlDirection.xlToRight)
.get_End(XlDirection.xlDown);
// holds the range of cells in the worksheet
Range tableRange = sheet.Range(range, rngLastCell);
try
{
foreach(var cell in tableRange.Rows)
{
Console.Write(cell.Value.ToString());
}
}
catch(Exception e)
{
Console.WriteLine("Something went wrong" + e.StackTrace);
}
}
}
}
Here is the console output:
Your problem is here:
foreach(var cell in tableRange.Rows)
{
Console.Write(cell.Value.ToString());
}
This is looping through the rows of the range, each of which is a range itself, so the "value" is an array. The default implementation of ToString
for an array is to just print the name of the type, which is System.Object[,]
.
This should work since Range.Value
will be an array of objects:
foreach(object cell in ((object[,])tableRange.Value))
{
Console.Write(cell.ToString());
}
Note that it also saves the overhead of calling .Value
on each cell , which is an expensive operation. It's much more efficient to get the value of the entire range into an array and loop over that .
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.