[英]C# System.Object[,]
我寫了一個C#程序,它打開一個Excel工作簿和一個工作表,並遍歷工作表中的所有單元格,並打印出每個單元格中的值。
我遇到的問題是控制台正在打印System.Object[,]
而不是實際的單元格值,這似乎是一個無限循環。
有誰知道為什么不打印實際值?
這是我的程序:
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);
}
}
}
}
這是控制台輸出:
您的問題在這里:
foreach(var cell in tableRange.Rows)
{
Console.Write(cell.Value.ToString());
}
這是遍歷范圍的行 ,每個行本身就是一個范圍,因此“值”是一個數組。 數組的ToString
的默認實現是僅打印類型的名稱,即System.Object[,]
。
這應該起作用,因為Range.Value
將是一個對象數組:
foreach(object cell in ((object[,])tableRange.Value))
{
Console.Write(cell.ToString());
}
請注意,這還節省了在每個單元格上調用.Value
的開銷,這是一項昂貴的操作。 這是更有效地將整個范圍內的值到一個數組,遍歷這一點 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.