C#Interop定义了一个工作表数组

时间:2017-03-09 14:08:04

标签: c# excel interop vsto

如何使用4 worksheets定义数组?

例如,这些是worksheets

    var wb = (Excel.Workbook)Globals.ThisAddIn.Application.ActiveWorkbook;
    var wsEvars = wb.Sheets["Evars"];
    var wsProps = wb.Sheets["Props"];
    var wsEvents = wb.Sheets["Events"];
    var wsListVars = wb.Sheets["List Vars"];

我希望将它们包含在数组中,如下所示:

var sheets = [wsEvars, wsProps, wsEvents, wsListVars];

2 个答案:

答案 0 :(得分:1)

有了这些参考资料......

using Microsoft.Office.Tools.Excel;
using System.Linq;
using Worksheet = Microsoft.Office.Tools.Excel.Worksheet;
using Excel = Microsoft.Office.Interop.Excel;

如果你只需要com对象就可以......

var wsEvars = wb.Sheets["Evars"];
var wsProps = wb.Sheets["Props"];
var wsEvents = wb.Sheets["Events"];
var wsListVars = wb.Sheets["List Vars"];

var sheets = new Excel.Worksheet[] {wsEvars, wsProps, wsEvents, wsListVars};

如果您需要VSTO主机界面......

var _factory = Globals.Factory;    

var wsEvars = _factory.GetVstoObject(wb.Sheets["Evars"]);
    var wsProps = _factory.GetVstoObject(wb.Sheets["Props"]);
    var wsEvents = _factory.GetVstoObject(wb.Sheets["Events"]);
    var wsListVars = _factory.GetVstoObject(wb.Sheets["List Vars"]);

    var sheets = new Worksheet[] {wsEvars, wsProps, wsEvents, wsListVars};

或者使用linq ......

var _sheetsArray = new[]{"wsEvars", "wsProps", "wsEvents", "wsListVars"}.Join(
    _wb.Worksheets.Cast<Excel.Worksheet>(), // outer  
    name => name, s => s.Name,              // key accessors
    (tag, s) => _factory.GetVstoObject(s)   // output selector
).ToArray();

答案 1 :(得分:0)

您可以按如下方式声明和初始化数组:

var sheets = new Microsoft.Office.Interop.Excel.Sheets[] { wsEvars, wsProps, wsEvents, wsListVars };