connectrion my C# code to external Excel file - c#

I use to Open Excel files from my C# Interop application.
However, I cannot pick up (or get connected to) Excel file, when it is already "in air" - open manualy.
app = new Excel.Application();
foreach(var w in app.Workbooks)
{
if(w.name == "MyFile") found = true; //never ever found
}
Could you please advice How To get connected to MyFile.xlsx, not just Open it?

Related

c # interop Can you tell which file excel is running using excel?

I want to quit Excel, which is opening certain files when there are a lot of excel running.
I know how to run Excel excel and know how to terminate the process, but I do not know how to exit excel that reads certain files.
I wonder if there is a way to shut down excel (or office) running a particular file through an interop or some other way.
Excel is a red herring here, what you're actually looking to do is discover which running process has locked a particular file on disk. It doesn't matter that it's an excel file in particular. This is a fairly common requirement and is well covered in other SO answers such as:
How do I find out which process is locking a file using .NET?
This is what you want:
foreach (var process in Process.GetProcessesByName("EXCEL"))
{
process.Kill();
}
To close a specific/particular excel file
private static void KillSpecificExcelFileProcess(string excelFileName)
{
var processes = from p in Process.GetProcessesByName("EXCEL")
select p;
foreach (var process in processes)
{
if (process.MainWindowTitle == excelFileName.Substring(0, excelFileName.IndexOf(".")) + " - Excel" )
process.Kill();
}
}
Pass the File name in the method call and in result the specific process will be close/kill

Excel File created as read only

I have created an Excel Add-in using VSTO in C#. I want to create a new Excel file from a template located on a SharePoint site. A file picker dialog box is used so the user can chose which file to use as a template. Everything works fine exept the new workbook is created as read only. If I copy the template file on my computer, and use the same program to pick that file as a template, the new workbook is not created as read only.
The file on the sharePoint is not being open elseware when creathing the new file. Is there a way to specify the sharePoint library is a safe source? Or to set the newly created workbook readonly property to false?
{
string pathSP= #”\\Business.sharepoint.com#SSL\teams\group\NDC\”;
if (System.IO.Directory.Exists(pathSP))
{
Excel.Application excelObj = Globals.ThisAddIn.Application;
Office.FileDialog fileDialog = excelObj.FileDialog[Office.MsoFileDialogType.msoFileDialogFilePicker];
fileDialog.InitialFileName = initialPath;
fileDialog.AllowMultiSelect = false;
fileDialog.InitialView = Office.MsoFileDialogView.msoFileDialogViewDetails;
fileDialog.Title = "Create Excel file from template";
fileDialog.Filters.Clear();
fileDialog.Filters.Add("Excel template", "*.xls; *.xlsx; *.xlsm; *.xltx; *.xltm; *.xlt", 1);
string TemplatePath;
if (fileDialog.Show() == -1)
{
templatePath = fileDialog.SelectedItems.Item(1);
fileDialog = null;
}
else
{
templatePath=""
fileDialog = null;
}
if (templatePath != "")
{
Excel.Workbook ws= excelObj.Workbooks.Add(templatePath);
}
}
else
{
MessageBox.Show("SharePoint site is not available", "Create Excel file from template", MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
for the two ways you mentioned:
set the share point library as a safe source - this can be achieved by setting the excel setting: Options -> Trust Centre -> Trust Centre Settings -> Trusted Locations -> add the sharepont location
set the file access (readonly=false) at the end of your process
Actually as a general practice when dealing with template file (not limited to excel), the system should copy the template file to a local temp location (ideally the running user's TEMP folder), use it and then delete it afterwards. this way would avoid all kinds of problems such as file-lock-by-other-user/process problems.
So I think your problem is the Workbooks.Add(). Check out what Microsoft says about it:
[Workbooks.Add()] Determines how the new workbook is created. If this argument is a string specifying the name of an existing Microsoft Excel file, the new workbook is created with the specified file as a template.
I believe the workbook you're creating is a carbon copy of whatever the sharepoint server has, including permissions. The fact it works locally is another clue that sharepoint might be fiddling with permissions.
I suggest try saving a copy of the file locally. You can even use the SaveFileDialog object to give the user a GUI to save their new copy.
SaveFileDialog userSaveFileDialog = new SaveFileDialog();
userSaveFileDialog.Filter = "Excel 2007 and later | *.xlsx, Excel Macro Enabled Worksheet | *.xlsm, I'm guessing this is a 2007 template | *.xltx, Template Macro maybe | *.xltm, I almost definitely think this is a template file | *.xlt";
userSaveFileDialog.Title = "Save an Excel File";
userSaveFileDialog.ShowDialog();
this.Application.ActiveWorkbook.SaveCopyAs(#userSaveFileDialog.FileName);
Once you're done, you can programmatically open the newly saved workbook using userSaveFileDialog.FileName as your filepath.

C# - Kill EXCEL.exe process referencing a particular file

I have a C# application that creates an excel file. But if the file is left open and the app is run the second time, it throws IO exception (since, in the code I am replacing the existing file with new one)
Now, I want to check if the file is open and kill the excel.exe process that is referencing this file.
Is there any way this can be achieved?
Note: There might be several excel files open. I want to close only the process that is using my file.
xlFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
File.Copy(xlFilePath + "\\file.xlsx", String.Format("{0}\\OutputFile{1}.{2}.xlsx", xlFilePath, DateTime.Now.Year, DateTime.Now.Month), true);
xlFilePath = Path.Combine(xlFilePath, String.Format("{0}\\OutputFile{1}.{2}.xlsx", xlFilePath, DateTime.Now.Year, DateTime.Now.Month));
appl = new Excel.Application(Visible = false);
wbookss = appl.Workbooks;
wbook = wbookss.Open(xlFilePath);
//Excel.Worksheets wsheetss = appl.Worksheets;
wsheet = wbook.Sheets["Sheet1"];
Application_GenerateReport(wsheet);
Clipboard.Clear();
wbook.Close(true);
wbookss.Close();
appl.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(wsheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wbookss);
System.Runtime.InteropServices.Marshal.ReleaseComObject(appl);
EDIT: The file remains open if there was an exception in the last run. If it is opened by a user, it can be killed by checking the MainWindowTitle property (As suggested by Yeldar).
Another solution could be:
System.Diagnostics.Process.Start("CMD.exe","taskkill /f /im excel.exe");
This line will call command prompt and running the command taskkill.
All opening excel programs will be killed in this way.
Updated: (For one file)
System.Diagnostics.Process.Start("CMD.exe","taskkill /FI "WindowTitle eq Microsoft Excel - filename.xls");
As Excel stores the name of the opened file in its title like this:
Microsoft Excel - filename.xls
You can iterate through the processes and kill the one with the given name:
string filename = "mylist.xls";
var excelProcesses = Process.GetProcessesByName("excel");
foreach (var process in excelProcesses)
{
if (process.MainWindowTitle == $"Microsoft Excel - {filename}") // String.Format for pre-C# 6.0
{
process.Kill();
}
}
Note that:
it will also close all opened files with the same name
it will abandon any changes that user could change
title of Excel window may (or not, not sure, need to check) vary from version to version
However, as I said in comments, it is better to fix causes, but not consequences - just make your program start new Excel application without errors.

How to connect to an Excel workbook that lives in SharePoint 2013 and update it

I am creating a command line application and I would like to connect to a SharePoint site that has a workbook that I want to update.
I don't even know where to start but I guess the questions I have are.
What API can I use for this? It has to be something that is already built-in and not a third party API if possible :)
Once the connection is done and I am able to open the spreadsheet, will I be able to also switch from one sheet to another?
I've tried to use some code like this but it did not work.
private static void GetExcelSheetNames(string filename)
{
var xls = new Microsoft.Office.Interop.Excel.Application();
xls.Visible = true;
xls.DisplayAlerts = false;
var workbook = xls.Workbooks.Open(Filename: filename, IgnoreReadOnlyRecommended: true, ReadOnly: false);
try
{
// Refresh the data from data connections
workbook.RefreshAll();
// Wait for the refresh occurs - *wish there was a better way than this.
System.Threading.Thread.Sleep(5000);
// Save the workbook back again
workbook.SaveAs(Filename: filename); // This is when the Exception is thrown
// Close the workbook
workbook.Close(SaveChanges: false);
}
catch (Exception ex)
{
//Exception message is "Cannot save as that name. Document was opened as read-only."
}
finally
{
xls.Application.Quit();
xls = null;
}
}
The Exception that I get was:
Microsoft Excel cannot access the file 'https//url/bla/bla/bla/workbook.xlsx There are several possible reasons:
The file name or path does not exist.
The file is being used by another program.
The workbook you are trying to save has the same name as a currently open workbook.
Actually, it seems like it is trying to open an instance of Excel Desktop in my machine.
Sorry for such an open question but I don't really know how can I connect to a SharePoint site.
Thanks in advance!
If you're using a document in a document library, check to make sure that it is checking out the document before you try to save it. I am working with a similar process but using a report library instead of a document library and am able to save documents without check out/in.

disabling overwrite existing file prompt in Microsoft office interop FileSaveAs method

I am using Ms Office Interop assemblies to create a MS Project file. To save the file created, I am using FileSaveAs method and it prompts a message saying that if you want to replace the existing file.
I want to suppress the message, and I didn't find any parameter in FileSaveAs method for this purpose.
Any Idea on this?
I'am using C# as my programming language.
I ran into this issue when working with Excel Interop. The best I've been able to find is to disable all Office alerts, like this:
Microsoft.Office.Interop.MSProject.Application msProjectApp = new Microsoft.Office.Interop.MSProject.Application();
msProjectApp.DisplayAlerts = false;
Never double dot COM objects, as they will not be released and this will leave excel open on your server. Unfortunately I have crashed servers because of this.
private void InitialiseExcel()
{
if (excelApp == null)
excelApp = new Excel.Application();
// Turn off User Prompts
excelApp.DisplayAlerts = false;
// Turn off screen updating so we do not get flicker
var app = excelApp.Application;
app.ScreenUpdating = false;
// Specifies the state of the window;
excelApp.WindowState = Excel.XlWindowState.xlMinimized;
Marshal.ReleaseComObject(app);
}

Categories

Resources