Getting Excel object from Process

The following Coding will help to get Excel object from process,

fisrt define External variables,

public delegate bool EnumChildCallback(int hwnd, ref int lParam);

[System.Runtime.InteropServices.DllImport("User32.dll")]
public static extern bool EnumChildWindows(int hWndParent, EnumChildCallback lpEnumFunc, ref int lParam);

private EnumChildCallback cb;

[System.Runtime.InteropServices.DllImport("User32.dll")]
public static extern int GetClassName(int hWnd, StringBuilder lpClassName, int nMaxCount);

[System.Runtime.InteropServices.DllImport("Oleacc.dll")]
public static extern int AccessibleObjectFromWindow(int hwnd, uint dwObjectID, byte[] riid,
ref Excel.Window ptr);


and below function will get the excel object,

private Void fnGetExcelDataFromProcess()
{
string[] fileNames = new string[2];
fileNames[0]="A.xls";
fileNames[1]="B.xls";

for (int m = 0; m < fileNames.Length; m++)
{

System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
foreach (System.Diagnostics.Process prc in proc)
{
int hwnd = (int)prc.MainWindowHandle;
reader = null;
if (hwnd != 0)
{
int hwndChild = 0;
cb = new EnumChildCallback(EnumChildProc);
EnumChildWindows(hwnd , cb , ref hwndChild);
if (hwndChild != 0)
{
const uint OBJID_NATIVEOM = 0xFFFFFFF0;
Guid IID_IDispatch = new Guid("{00020400-0000-0000-C000-000000000046}");
Excel.Window ptr = null;
int hr = AccessibleObjectFromWindow(hwndChild , OBJID_NATIVEOM , IID_IDispatch.ToByteArray() , ref ptr);
if (hr >= 0)
{
xl = ptr.Application;
Excel.Workbooks wb = (Excel.Workbooks)xl.Workbooks;
for (int i = 1;i <= wb.Count;i++)
{
if (wb[i].Name.ToUpper().Contains(fileNames[m].ToUpper()))
{
wb[i].SaveCopyAs("D:\\test.xls");
break;
}
}
}
}
}
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: