首页 > 解决方案 > 我们如何使用 C# 运行现有 Excel 工作表的 excel 宏?

问题描述

嗨,我正在尝试使用 C#(Visual Studio)自动打开一个 Excel 工作簿并为 Web 应用程序运行其宏,有人可以建议这是否可行。

标签: c#asp.netexcel

解决方案


嗨,我在网上找到了一个解决方案,用于如何运行已经存在的应用程序的 Excel 宏,并运行它的宏。

这里的宏名称是:来自工作簿 Macro.xlsm 的宏

下面是代码片段:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;


 namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btn_Click(object sender, EventArgs e)
    {

        //~~> Define your Excel Objects
        Excel.Application xlApp = new Excel.Application();

        Excel.Workbook xlWorkBook;

        //~~> Start Excel and open the workbook.
        xlWorkBook = xlApp.Workbooks.Open("C:\\Users\\d.b.venkatachalam\\Desktop\\Macro.xlsm");
        xlApp.Visible = true;

        //~~> Run the macros by supplying the necessary arguments
        xlApp.Run("Macro");

    }
  }
}

推荐阅读