How to know whether an Excel file is open and close it automatically?

In my application, I should write data to an Excel file. I can pause the application, and go to open the Excel file to see the data I received.

However, when I start the application again with the Excel file open, there will be erros shown:

"My application" has encountered a problem and needs to close. We are sorry for the inconvenience.

It seems the application can not write data to an Excel file with the file is open...(no such problem with text file)

Q1. How to check whether an Excel file is open or not

Q2. How to close the Excel file automatically and then write data to the file again

Thanks in advance!




Answer this question

How to know whether an Excel file is open and close it automatically?

  • M. Abraham

    Oh, thanks, close to my problem

    // Get all instances of Notepad running on the local
    // computer.
    Process [] localByName = Process.GetProcessesByName("notepad");

    However, this will get all the instances of Notepad running on the computer...

    I just want to get the special instance of the Excel...

    If I kill the process, all the Excel files will be closed...

    How to get the specific Excel file and close only this one



  • rattatosk

    just thinking at the top of my head for now, not guarenteed to work but have you tried to specify the FileShare enumerator in the FileStream constructor

    Take a look at the 4th parameter in the Constructor of the FileStream and play with it.



  • medarch

    I looked around and try "file.open()" and "FileOpenDialog()", however, they are not the one I want...

    Anyone has some idea



  • JD653687

    one way to check to see if the process of excel is open is to use the Process.GetProcessesByName (System.Diagnosticks namespace) find it then kill it.

  • mcnamaragio

    this code goes through each instance of excel and closes the Workbooks you should add some code that checks for the document and selectively close that one.

    using System;

    using System.Collections;

    using System.Collections.Generic;

    using System.Text;

    using System.Runtime.InteropServices;

    using System.Runtime.InteropServices.ComTypes;

    using Microsoft.Office.Interop.Excel;

    namespace ConsoleApplication5

    {

    class Program

    {

    [DllImport("ole32.dll")]

    public static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);

    [DllImport("ole32.dll")]

    public static extern int CreateBindCtx(int reserved, out IBindCtx ppbc);

    public static Hashtable GetRunningObjectTable()

    {

    Hashtable result = new Hashtable();

    IntPtr numFetched = IntPtr.Zero;

    IRunningObjectTable runningObjectTable;

    IEnumMoniker monikerEnumerator;

    IMoniker[] monikers = new IMoniker[1];

    GetRunningObjectTable(0, out runningObjectTable);

    runningObjectTable.EnumRunning(out monikerEnumerator);

    monikerEnumerator.Reset();

    while (monikerEnumerator.Next(1, monikers, numFetched) == 0)

    {

    IBindCtx ctx;

    CreateBindCtx(0, out ctx);

    string runningObjectName;

    monikers[0].GetDisplayName(ctx, null, out runningObjectName);

    object runningObjectVal;

    runningObjectTable.GetObject(monikers[0], out runningObjectVal);

    result[runningObjectName] = runningObjectVal;

    }

    return result;

    }

    static void Main(string[] args)

    {

    Hashtable rot = GetRunningObjectTable();

    foreach (object o in rot.Values)

    {

    Application a = o as Application;

    if (a != null)

    {

    Workbooks wbooks = a.Workbooks;

    foreach (Workbook wb in wbooks)

    {

    wb.Close(false, Type.Missing, Type.Missing);

    }

    //a.DisplayAlerts = false;

    //a.Quit();

    }

    }

    }

    }

    }



  • Abdul Muheed

    Well, when I open the file while writing data to it, there will be "IOException was unhandled" errors says:

    "The process cannot access the file 'C:\Thursday, September 14, 2006.xls' because it is being used by another process."

    I tried "fileshare.None", "fileshare.read"...However, it does not work as expected.

    Just think,

    1. Run the application
    2. The file "'C:\Thursday, September 14, 2006.xls" is created.
    3. Data are written to the file
    4. Pause the application
    5. Open the .xls file to see the data received
    6. Start again the application(the .xls file is still open)
    7. The unhandled exception occurs and the application has to be closed

    I want to add a check before writing data to the .xls file to see whether it is open or not, if it is open, the file should be closed first and then the application will run and write data to the file. So that no unhandled exception will occur.

    Please do not think I will write to and open the file at the same time by the same application!

    I use the application to write data to an Excel file, and then try to use Microsoft Excel to open the file. Two applications use the same file at the same time. Then, some errors occur.



  • Learning VB

    you really shouldnt be doing this...if it is yourself that wants to check the file..check it after the application has done its job. I know this isnt a solution but just a thing to think about.

    I guess to kill an instance of excel would be to look for a window using P/Invoke - FindWindow - which will find the exact string you supply it to find the application. Once done, try to get the handle for it and then kill that handle via the Process

    http://www.pinvoke.net/default.aspx/user32/FindWindow.html

    Then get the instances of Excel, go through each handle, if the handle matches the handle returned by the API FindWindow, kill it.

    Remember, this may or may not work. I personally wouldn't recommend it - not best practice



  • Chuck Cobb

    Below is the code to receive data from the COM Port and write it to an Excel file...

    During the application, when I close the COM Port and go to C:\ and open the Excel file created by the application, I can see the data I received just now. Then when I open the COM Port again and forget to close the Excel file, the application will show error message and is forced to close. If I run the "Debug", the error message tells that the Excel file is in use and the application can not write data to it...

    Am I clear I think it has nothing to do with my code...I need to add one more function to check whether the Excel file data should be written to is open or not...

    The error exists even I do nothing to the Excel file by just opening it...

    public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)

    {
    //This method will be called when there is data waiting in the port's buffer
    comport.ReadTimeout = 300;
    String s = comport.ReadExisting();
    CM.Log(LogMsgType.Incoming, s);
    string path = @"C:\" + DateTime.Now.ToLongDateString() + ".xls";
    if (!File.Exists(path))
    {
    FileStream file = new FileStream(path, FileMode.Append, FileAccess.Write);
    {
    StreamWriter sw = new StreamWriter(file);
    sw.WriteLine(String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}", "Time", "Channel 0", "Channel 1", "Channel 2", "Channel 3", "Channel 4", "Channel 5", "Channel 6", "Channel 7"));
    sw.Flush();
    sw.Close();
    }
    }

    using (StreamWriter sw = new StreamWriter(path,true))
    {
    string[] parts = s.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
    foreach (string part in parts)
    {
    //convert the string to character array
    char[] a = part.ToCharArray();
    //get the length of the array
    int i = (int)a.Length;
    //convert hex string to int number
    string p = "";
    string blank = " ";
    for (int j = 0; j < (i-1); j++)
    {
    p = p + a[j];
    }
    string choose = Convert.ToString(a[i - 1]);
    int dec = int.Parse(p, System.Globalization.NumberStyles.HexNumber);
    switch (choose)
    {
    case "0": sw.WriteLine("{0}\t{1}", DateTime.Now.ToLongTimeString(), dec);
    break;
    case "1": sw.WriteLine("{0}\t{1}\t{2}", DateTime.Now.ToLongTimeString(), blank, dec);
    break;
    case "2": sw.WriteLine("{0}\t{1}\t{2}\t{3}", DateTime.Now.ToLongTimeString(), blank, blank, dec);
    break;
    case "3": sw.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", DateTime.Now.ToLongTimeString(), blank, blank, blank, dec);
    break;
    case "4": sw.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}", DateTime.Now.ToLongTimeString(), blank, blank, blank, blank, dec);
    break;
    case "5": sw.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", DateTime.Now.ToLongTimeString(), blank, blank, blank, blank, blank, dec);
    break;
    case "6": sw.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}", DateTime.Now.ToLongTimeString(), blank, blank, blank, blank, blank, blank, dec);
    break;
    case "7": sw.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}", DateTime.Now.ToLongTimeString(), blank, blank, blank, blank, blank, blank, blank, dec);
    break;
    default: CM.Log(LogMsgType.Error, "\nThe Incoming data is with wrong format\n Channel not tested\n");
    break;

    }

    }


    }

    Thank you!



  • Tony512

    how are you opening the file for writing Whats the code

  • How to know whether an Excel file is open and close it automatically?