如何改进代码C#以打开指定的excel文件,而不仅仅是打开excel应用程序

问题描述

我对此很陌生。我想创建一个Microsoft Excel加载项,该加载项会打开一个特定的Excel文件并写入一些数据。问题是我的代码仅打开excel应用程序而不打开指定文件 这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;

namespace ExcelAddInTrial
{
public partial class ThisAddIn
{
    private void ThisAddIn_Startup(object sender,System.EventArgs e)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\User\Desktop\Projects\Microsoft\B1.xlsx");
    }


    private void ThisAddIn_Shutdown(object sender,System.EventArgs e)
    {

    }

    #region VSTO generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }

    #endregion
}
}

我知道一些python,但是C#绝对是另一个挑战,

感谢您的帮助!

解决方法

您声明了Excel.Application xlApp;,但不对其进行初始化。 CLR不知道xlApp行中的xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\User\Desktop\Projects\Microsoft\B1.xlsx");是什么。
Excel.Application xlApp;替换为Excel.Application xlApp = Application;

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...