我编写了一个 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());
}
请注意,它还节省了在每个 cell 上调用 .Value
的开销,这是一项昂贵的操作。将整个范围的值放入数组并遍历 that 会更有效率。
关于C# 系统对象[,],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25856461/