遍历所有打开的excel工作簿

时间:2017-10-31 11:08:28

标签: c# excel add-in

我尝试使用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集合中的

不是工作簿。代码不会循环...

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

只需将一个ListBox添加到您的表单中,弹出此代码即可开始营业。

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());
            }
        }
    }
}