简体   繁体   中英

How to save excel file without GUI notifications?

I have an app that is running on a server and that has to write some stuff to excel files. When I want to save and close files I'm getting trouble when the files are open by other machines and users. Excel opens dialogs to ask for filenames but it is running on a server there is no user to close the dialogs. So when the file is open and cannot be written to it should be skipped with no GUI asking for filenames.

Workbook book = excel.Workbooks.Open(filename);
Worksheet sheet = (Worksheet) book.Worksheets.get_Item(1);
// write stuff in cells
book.SaveAs(filename);
book.Close(false);

How can I make excel to try to save the file and then close is no matter what ?

(In my app there is no lost data, it can be written to the excel files later anyways)


  • file exists → overwrite
  • file open → don't save, just close

Looks like this answers the question, check if the file is in use before you choose to save or skip.

Is there a way to check if a file is in use?

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

To check if a file exists you can use

if (File.Exists(filename)){
    // if the file exists
    book.Save();
}
else{
//if the file doesnt exist
    book.SaveAs(filename);
}

All problems might be solved if I set the share options for the one file that I must update. So that multiple users can update the file simultaneously: Menu → Extra → ...


This doesn't solve the problem to 100% but better than nothing:

 private static void saveAndClose(Workbook book, string filename) { try { File.Delete(filename); } catch { } if (!File.Exists(filename)) book.SaveAs(filename); book.Close(false); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM