在 C# 中访问打开的 Excel 工作簿

发布于 2024-11-20 13:49:12 字数 473 浏览 9 评论 0原文

我需要访问一个已经打开的 Excel 文件。我以为只要检查 .Workbooks 属性,它就会在那里,但事实并非如此。获取对打开工作簿的引用的正确方法是什么?

var app = new Microsoft.Office.Interop.Excel.Application();

// the count is 0 =(
app.Workbooks.Count == 0;

编辑

我可以通过...获取对Excel应用程序的引用...

app = (Excel.Application)Marshal.GetActiveObject("Excel.Application");

但是app.Workbooks.Count仍然是0为什么它不能获取对打开的工作簿的引用?

I need to access an excel file that is already open. I thought just inspecting the .Workbooks property that it would be there but it isn't. What is the right way to get a reference to the open workbook?

var app = new Microsoft.Office.Interop.Excel.Application();

// the count is 0 =(
app.Workbooks.Count == 0;

EDIT

I can get a reference to the Excel Application via...

app = (Excel.Application)Marshal.GetActiveObject("Excel.Application");

but app.Workbooks.Count is still 0 why isn't it able to get a reference to the opened workbook?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

哆啦不做梦 2024-11-27 13:49:13

添加到 Armbrat 的解决方案中;这对我有用:

// To use currently running instance of Excel 
Excel.Application objApp = 
(Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    Excel.Workbooks objBooks;    
    Excel._Workbook objBook;
            
objBooks = objApp.Workbooks;    // Adds to the workbooks collection - objBooks.Count will now == 1

objBook = objBooks["Name of workbook"]; // No filename extension, just the name shown in the workbook window title bar

To add to Armbrat's solution; this worked for me:

// To use currently running instance of Excel 
Excel.Application objApp = 
(Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    Excel.Workbooks objBooks;    
    Excel._Workbook objBook;
            
objBooks = objApp.Workbooks;    // Adds to the workbooks collection - objBooks.Count will now == 1

objBook = objBooks["Name of workbook"]; // No filename extension, just the name shown in the workbook window title bar
扛起拖把扫天下 2024-11-27 13:49:13

我知道它的老问题,但我只是发布我的解决方案
我的解决方案是

  1. ,则在 Excel 应用程序对象上执行“Marshal.GetActiveObject”
  2. 如果没有找到工作簿
  3. ,释放 Excel 应用程序 hwnd 并再次获取活动对象
    我希望它有帮助

i know its old question but i just post my solution
my solution was

  1. do "Marshal.GetActiveObject" at excel application object
  2. if there is no workbook found
  3. then, release excel application hwnd and do get active object again
    i hope it helpful
我ぃ本無心為│何有愛 2024-11-27 13:49:13
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();

// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);

// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

// see the excel sheet behind the program
app.Visible = true;

// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;

// changing the name of active sheet
worksheet.Name = "Exported from gridview";

try
{
    // storing header part in Excel
    for (int i = 1; i < dgvRESULTS.Columns.Count + 1; i++)
    {
        worksheet.Cells[1, i] = dgvRESULTS.Columns[i - 1].HeaderText;
        worksheet.Cells[1, i].Interior.Color = System.Drawing.Color.LightYellow;
    }

    // storing Each row and column value to excel sheet
    for (int i = 0; i < dgvRESULTS.Rows.Count - 1; i++)
    {
        for (int j = 0; j < dgvRESULTS.Columns.Count; j++)
        {
            if (dgvRESULTS.Rows[i].Cells[j].Value != null)
            {
                worksheet.Cells[i + 2, j + 1] = dgvRESULTS.Rows[i].Cells[j].Value.ToString();
                //worksheet.Cells[i + 2, j + 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(dgvRESULTS.Rows[i].DefaultCellStyle.BackColor);
            }
            else
            {
                worksheet.Cells[i + 2, j + 1] = "";
            }
        }
    }
}
catch(NullReferenceException ne)
{
}
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// save the application
workbook.SaveAs(filePath +"\\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

// Exit from the application
app.Quit();
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();

// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);

// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

// see the excel sheet behind the program
app.Visible = true;

// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;

// changing the name of active sheet
worksheet.Name = "Exported from gridview";

try
{
    // storing header part in Excel
    for (int i = 1; i < dgvRESULTS.Columns.Count + 1; i++)
    {
        worksheet.Cells[1, i] = dgvRESULTS.Columns[i - 1].HeaderText;
        worksheet.Cells[1, i].Interior.Color = System.Drawing.Color.LightYellow;
    }

    // storing Each row and column value to excel sheet
    for (int i = 0; i < dgvRESULTS.Rows.Count - 1; i++)
    {
        for (int j = 0; j < dgvRESULTS.Columns.Count; j++)
        {
            if (dgvRESULTS.Rows[i].Cells[j].Value != null)
            {
                worksheet.Cells[i + 2, j + 1] = dgvRESULTS.Rows[i].Cells[j].Value.ToString();
                //worksheet.Cells[i + 2, j + 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(dgvRESULTS.Rows[i].DefaultCellStyle.BackColor);
            }
            else
            {
                worksheet.Cells[i + 2, j + 1] = "";
            }
        }
    }
}
catch(NullReferenceException ne)
{
}
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// save the application
workbook.SaveAs(filePath +"\\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

// Exit from the application
app.Quit();
手心的温暖 2024-11-27 13:49:12

检查现有实例,而不是实例化新实例:

try
{
  Microsoft.Office.Interop.Excel.Application app = 
      System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch
{
  // Excel is not running.
}

Instead of instantiating a new instance, check for an existing one:

try
{
  Microsoft.Office.Interop.Excel.Application app = 
      System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch
{
  // Excel is not running.
}
岁吢 2024-11-27 13:49:12

试试这个代码:

using Excel = Microsoft.Office.Interop.Excel;

public Excel.Application xlApp;
public Excel.Workbook xlWorkBook;
public Excel.Worksheet xlWorkSheet;

public void ExcelTransferData()
{
   xlApp = new Microsoft.Office.Interop.Excel.Application();
   xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

   foreach (Excel.Workbook item in xlApp.Workbooks)
   {
        //Select the excel target 'NAME'
        if (item.Name == "Template.xlsx")
        {
            xlWorkBook = item; 
            break;
        }

        //Select the target workbook
        xlWorkSheet = xlWorkBook.Sheets[1] as Excel.Worksheet;
        //Set cell value
        xlWorkSheet.Cells[5, 1] = "davinceleecode";
   }
}

Try this code:

using Excel = Microsoft.Office.Interop.Excel;

public Excel.Application xlApp;
public Excel.Workbook xlWorkBook;
public Excel.Worksheet xlWorkSheet;

public void ExcelTransferData()
{
   xlApp = new Microsoft.Office.Interop.Excel.Application();
   xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

   foreach (Excel.Workbook item in xlApp.Workbooks)
   {
        //Select the excel target 'NAME'
        if (item.Name == "Template.xlsx")
        {
            xlWorkBook = item; 
            break;
        }

        //Select the target workbook
        xlWorkSheet = xlWorkBook.Sheets[1] as Excel.Worksheet;
        //Set cell value
        xlWorkSheet.Cells[5, 1] = "davinceleecode";
   }
}
撩起发的微风 2024-11-27 13:49:12
 String constr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+txtSourceFile.Text+";Extended Properties='Excel 8.0;HDR=YES;';";
        String constr2 = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtLibrary.Text + ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbConnection con2 = new OleDbConnection(constr2);
        OleDbConnection con3 = new OleDbConnection(constr);

        OleDbCommand oconn = new OleDbCommand("Select * From [eudra$]", con);
        OleDbCommand oconn2 = new OleDbCommand("Select * From [Sheet1$]", con2);
        OleDbCommand oconn3 = new OleDbCommand("Select * From [eudra$] where EXAMPARM in ('with one or more serious adverse events','with one or more non-serious adverse events that met the incidence cutoff')", con);

        if (txtSourceFile.Text != "")
        {
            con.Open();
            con2.Open();
            con3.Open();

            OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
            OleDbDataAdapter sda2 = new OleDbDataAdapter(oconn2);
            OleDbDataAdapter sda3 = new OleDbDataAdapter(oconn3);


            DataTable data = new DataTable();
            sda.Fill(data);

            DataTable data2 = new DataTable();
            sda2.Fill(data2);

            DataTable data3 = new DataTable();
            sda3.Fill(data3);

            var test = JoinDataTables(data, data2, (row1, row2) => (row1.Field<string>("BODY_SYS").ToUpper() == row2.Field<string>("Term").ToUpper() ));

            data3.Merge(test, true);

            dgvImp.DataSource = data3;
            con.Close();
        }
 String constr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+txtSourceFile.Text+";Extended Properties='Excel 8.0;HDR=YES;';";
        String constr2 = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtLibrary.Text + ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbConnection con2 = new OleDbConnection(constr2);
        OleDbConnection con3 = new OleDbConnection(constr);

        OleDbCommand oconn = new OleDbCommand("Select * From [eudra$]", con);
        OleDbCommand oconn2 = new OleDbCommand("Select * From [Sheet1$]", con2);
        OleDbCommand oconn3 = new OleDbCommand("Select * From [eudra$] where EXAMPARM in ('with one or more serious adverse events','with one or more non-serious adverse events that met the incidence cutoff')", con);

        if (txtSourceFile.Text != "")
        {
            con.Open();
            con2.Open();
            con3.Open();

            OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
            OleDbDataAdapter sda2 = new OleDbDataAdapter(oconn2);
            OleDbDataAdapter sda3 = new OleDbDataAdapter(oconn3);


            DataTable data = new DataTable();
            sda.Fill(data);

            DataTable data2 = new DataTable();
            sda2.Fill(data2);

            DataTable data3 = new DataTable();
            sda3.Fill(data3);

            var test = JoinDataTables(data, data2, (row1, row2) => (row1.Field<string>("BODY_SYS").ToUpper() == row2.Field<string>("Term").ToUpper() ));

            data3.Merge(test, true);

            dgvImp.DataSource = data3;
            con.Close();
        }
梦纸 2024-11-27 13:49:12

第一个函数IsXlFileOpen会告诉你excel文件是否打开
或不。

第二个函数 GetXlSheet 将为您提供 Excel 应用程序,
工作簿和工作表输出,您可以从这里开始编码。

using System.Collections.Generic;
using System.IO;
using System.Linq;
using wf = System.Windows.Forms;
using xl = Microsoft.Office.Interop.Excel;

public static class ExcelTest
{   
    public xl.Application xlApp = null;
    public xl.Workbook xlWb = null;
    public xl.Worksheet xlWs = null;

    public static bool IsXlFileOpen(string xlFileName)
    {       
        try
        {       
            if (!File.Exists(xlFileName))
            {
                wf.MessageBox.Show("Excel File does not exists!");
                return false;
            }

            try
            {
                xlApp = (xl.Application)Marshal.GetActiveObject("Excel.Application");
            }
            catch (Exception ex)
            {
                return false;
            }

            foreach (xl.Workbook wb in xlApp.Workbooks)
            {
                if (wb.FullName == xlFileName)
                {
                    xlWb = wb;
                    return true;
                }
            }

            return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    public static void GetXlSheet(string xlFileName,
                                    string xlSheetName)
    {
        try
        {
            if (!File.Exists(xlFileName))
            {
                wf.MessageBox.Show("Excel File does not exists!");
                return false;
            }

            xlApp = (xl.Application)Marshal.GetActiveObject("Excel.Application");
            foreach (xl.Workbook wb in xlApp.Workbooks)
            {
                if (wb.FullName == xlFileName)
                {
                    if (!xlWb
                        .Sheets
                        .Cast<xl.Worksheet>()
                        .Select(s => s.Name)
                        .Contains(xlSheetName))
                    {
                        wf.MessageBox.Show("Sheet name does not exist in the Excel workbook!");
                        return;
                    }
                    xlWs = xlWb.Sheets[xlSheetName];
                }
            }
        }
        catch (Exception ex)
        {
            // catch errors
        }
    }   
}

The first function IsXlFileOpen will tell you whether the excel file is open
or not.

The second function GetXlSheet will get you the Excel application,
workbook and worksheet output, from where you can start coding.

using System.Collections.Generic;
using System.IO;
using System.Linq;
using wf = System.Windows.Forms;
using xl = Microsoft.Office.Interop.Excel;

public static class ExcelTest
{   
    public xl.Application xlApp = null;
    public xl.Workbook xlWb = null;
    public xl.Worksheet xlWs = null;

    public static bool IsXlFileOpen(string xlFileName)
    {       
        try
        {       
            if (!File.Exists(xlFileName))
            {
                wf.MessageBox.Show("Excel File does not exists!");
                return false;
            }

            try
            {
                xlApp = (xl.Application)Marshal.GetActiveObject("Excel.Application");
            }
            catch (Exception ex)
            {
                return false;
            }

            foreach (xl.Workbook wb in xlApp.Workbooks)
            {
                if (wb.FullName == xlFileName)
                {
                    xlWb = wb;
                    return true;
                }
            }

            return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    public static void GetXlSheet(string xlFileName,
                                    string xlSheetName)
    {
        try
        {
            if (!File.Exists(xlFileName))
            {
                wf.MessageBox.Show("Excel File does not exists!");
                return false;
            }

            xlApp = (xl.Application)Marshal.GetActiveObject("Excel.Application");
            foreach (xl.Workbook wb in xlApp.Workbooks)
            {
                if (wb.FullName == xlFileName)
                {
                    if (!xlWb
                        .Sheets
                        .Cast<xl.Worksheet>()
                        .Select(s => s.Name)
                        .Contains(xlSheetName))
                    {
                        wf.MessageBox.Show("Sheet name does not exist in the Excel workbook!");
                        return;
                    }
                    xlWs = xlWb.Sheets[xlSheetName];
                }
            }
        }
        catch (Exception ex)
        {
            // catch errors
        }
    }   
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文