我正在尝试使用 C# 构建 Excel 的加载项。我正在使用这个 tutorial .到目前为止还不错,但我对这部分代码有疑问:
private void PopulateWorkbooks()
{
var excel = Globals.ThisAddIn.Application;
var workbooks = excel.Workbooks;
foreach (var workbook in workbooks)
{
var book = workbook as Excel.Workbook;
if (book != null)
{
var workbookViewModel = new WorkbookViewModel(book);
this.workbookViewModels.Add(workbookViewModel);
}
}
}
workbooks
集合中没有工作簿。代码没有进入循环...
有什么想法吗?
只需将一个列表框添加到您的表单,弹出此代码,您就可以开始工作了。
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 Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Microsoft.Office.Interop.Excel.Application XL = null;
private void Form1_Load(object sender, EventArgs e)
{
XL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
foreach (Microsoft.Office.Interop.Excel.Workbook _wb in XL.Workbooks)
{
this.listBox1.Items.Add(_wb.Name.ToString());
}
}
}
}
我是一名优秀的程序员,十分优秀!