Accessing an open Excel Workbook in C#

前端 未结 5 1136
情话喂你
情话喂你 2020-12-09 06:51

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 w

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 07:35

    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";
       }
    }
    

提交回复
热议问题