C#与EXCEL交互出现问题

学习CAD二开需要与EXCEL交互,从Nuget下了netOffice库。
学习到以下代码,但是总是出错,不知道怎么处理,错误在
“Excel.Worksheet sheet =(Excel.Worksheet) book.Worksheets[1];”这一行,
错误的原因:NetOffice.NetOfficeException:“Factory is not initialized with NetOffice assemblies.”


using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = NetOffice.ExcelApi;

namespace _02创建图形
{
    public  class ExcelDemo
    {
        [CommandMethod("ExtToExcelDemo")]
        public void ExtToExcelDemo()
        {            
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook book = excelApp.Workbooks.Add();
            Excel.Worksheet sheet =(Excel.Worksheet) book.Worksheets[1];
            sheet.Cells[1, 1].Value = "吸湿性";
            book.Save();
            excelApp.Quit();
            excelApp.Dispose();
        }
    }
}

百度搜“NetOffice.NetOfficeException:“Factory is not initialized with NetOffice assemblies.””

【以下回答由 GPT 生成】

你好,根据你的代码和问题描述,错误信息"Factory is not initialized with NetOffice assemblies"表示你的代码中没有正确初始化NetOffice库。为了解决这个问题,你需要按照以下步骤进行操作:

  1. 首先,确保你已经在项目中添加了对NetOffice库的引用。你可以在Visual Studio中右键点击项目,然后选择"管理NuGet程序包",在NuGet包管理器中搜索"NetOffice"并安装。

  2. 在你的代码顶部,添加对NetOffice的引用,并指定命名空间。你需要使用下面的代码添加引用:

using NetOffice.ExcelApi;
  1. 接下来,我们需要在代码中创建一个NetOffice的Factory实例,并使用它去代替直接使用Excel.Application。修改你的代码如下:
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = NetOffice.ExcelApi;

namespace _02创建图形
{
    public class ExcelDemo
    {
        [CommandMethod("ExtToExcelDemo")]
        public void ExtToExcelDemo()
        {    
            // 创建一个Factory对象
            ExcelApi.Application excelApp = new ExcelApi.Application();
            NetOffice.InitializeExcel(excelApp);

            Excel.Workbook book = excelApp.Workbooks.Add();
            Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets[1];
            sheet.Cells[1, 1].Value = "吸湿性";
            book.Save();
            excelApp.Quit();
        }
    }
}

通过以上的修改,你的代码应该就可以正确执行了。确保你安装了NetOffice并正确的引用了它的命名空间。希望这可以帮助到你。如果你还有其他问题,请随时提问。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^