[英]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. 我有一个在服务器上运行的应用程序,必须将一些内容写入excel文件。 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.
Excel将打开对话框询问文件名,但该文件正在服务器上运行,没有用户可以关闭对话框。 So when the file is open and cannot be written to it should be skipped with no GUI asking for filenames.
因此,当文件打开且无法写入时,应在没有GUI要求文件名的情况下跳过。
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 ? 我怎样才能使excel尝试保存文件,然后无论如何都关闭?
(In my app there is no lost data, it can be written to the excel files later anyways) (在我的应用程序中,没有丢失的数据,以后仍然可以将其写入excel文件中)
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 → ...
这样多个用户可以同时更新文件:菜单→其他→...
private static void saveAndClose(Workbook book, string filename) { try { File.Delete(filename); } catch { } if (!File.Exists(filename)) book.SaveAs(filename); book.Close(false); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.