如何访问我的 Visual Studio Office Excel 工作簿中的 sheet 中的数据?

How to access data in sheet in my Visual Studio Office Excel workbook?

我需要用 C# 代码创建一个 "Document level customization"(不是 Excel 加载项!)

我创建了一个 Visual Studio Office Excel 2010 Workbook 项目类型。这会在我的项目中创建一个包含 3 张工作表的工作簿。我在其中一张纸上添加了一些 "configuration" 信息。

我需要以编程方式访问此配置信息(Sheet1包含一个button - 按下该按钮应该

  1. 加载配置数据
  2. 打开 WinForm
  3. 在该表单上显示配置数据,

但我不知道该怎么做...

如果我尝试初始化 Sheet1 class,编译器需要两个参数 - Microsoft.Office.Tools.Excel.FactoryIServiceProvider,但我是从放置在Sheet2 - 所以 after Excel 工作簿已经打开... Sheet1 不应该自动初始化吗?

那么,如何从我的 VSTO 项目的 C# 代码访问 Sheet1

编辑

Please see project sample screencast here

我在 Sheet2 上有一个按钮,应该

  1. 从 Sheet1 加载一些数据
  2. 初始化 WinForm
  3. 将其添加为该 WinForm 上 ComboBox 的数据源

我找不到如何从 Sheet1 读取数据的方法...

似乎没有多少开发人员(至少在 Whosebug 上)在 Visual Studio / VSTO 中使用 Excel 工作簿),但这仍然是我获得这个基本知识的方式工作正常 - 如果这对其他人有帮助

因为我的代码在 Worksheet 的 *.cs 文件中,所以我可以通过这种方式访问​​项目的 xlsx 文件:

var excel = (Excel.Application)this.Application;
var xlbook = (Excel.Workbook)excel.ActiveWorkbook; 

var worksheets = xlbook.Worksheets;
var sheet = (Excel.Worksheet)worksheets["Sheet3"];
int row = 2;//1st row for column titles

while (!string.IsNullOrEmpty(((Excel.Range)sheet.Cells[row, 2]).Value))
{
    var weight = ((Excel.Range)sheet.Cells[row, 3]).Value;
    row++;
}

关于在 c# 代码中处理来自 Excel sheet 的数据的一些其他事情,我发现(也许这对某人有帮助):

  1. Excel 单元格的 .NET 类型是 Excel.Range(至少我没有 找到任何其他选项)
  2. 当读取 Excel 文件中的空单元格时,它在 .NET 端的值为空,而不是“”
  3. 值在 Excel 端似乎是字符串 - 在 C# 端加载时可以变成不同的类型。我不知道这是不是最好的方法,但我是这样解决的:

var weight = (((Excel.Range)sheet.Cells[row, 3]).Value);

if (weight is double)
{
    product.Weight = ((double)((Excel.Range)sheet.Cells[row, 3]).Value).ToString();
}
else if (weight is string)
{
    product.Weight = ((Excel.Range)sheet.Cells[row, 3]).Value;
}