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
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()
.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
}
}
}