Opening an Excel file in C# using Process.Start - c#

I'm trying to open an excel file using a button click. And for some reason it's not working. I've tried several things. Any ideas why they are not working?
Method 1 I have tried. This opens the file manager but does not open the proper file. It is definitely using the proper path to the file and the file does exist
private string fileCopy;
public RepairResultsControl()
{
InitializeComponent();
}
public void Show(PSRepair.AnalysisResults analysis, string pathNameCopy)
{
fileCopy = pathNameCopy;
Show();
}
private void btnGoToFile_Click(object sender, EventArgs e)
{
Process.Start("explorer.exe", "/select,"+ fileCopy);
}
Method 2. This just didn't open anything not sure why
System.Diagnostics.Process.Start(#"C:\Users\username\Documents\newTest.xlsx");

Normally, Process.Start(#"C:\Users\username\Documents\newTest.xlsx"); would open your document in Excel.
However, you say in a comment that you are doing this from an Excel add-in which runs in the background. The solution needs to take this into account (the code sample assumes that you have a VSTO add-in, otherwise you need to adjust accordingly):
// make the running Excel instance visible
Globals.ThisAddIn.Application.Visible = true;
// open the workbook using Excel interop
Globals.ThisAddIn.Application.Workbooks.Open(fileName);

Try running as an admin
Check for exceptions, also the start method should return a bool, check to make sure it is true.
Make SURE your xlsx files are associated with Excel(easy check for this is at a command prompt, type in your filename and hit enter... if excel opens you are good)
Check your system error logs.

Related

Overwrite an file which is currently open and it use in c#

I am using C# to create a GUI which has a logging feature. When I create the log file, I provide it a filename. But I have the following issue. For instance, if the file is already open in the background on my desktop and I want to name my filename as the same, I get the exception message as following:
The process cannot access the file 'C:\blah\blah\mytest.csv' because it is being used by another process.
I am using the following piece of code to check if the file exists and using the streamwriter to create the new file.
if (FileUtils.Exists(fileName))
{
if (!FileUtils.Delete(fileName))
{
cout<< Error replacing log file, it might be used by another process";
}
}
//Exception handling
public static bool Delete(string myfiletowrite)
{
try
{
File.Delete(myfiletowrite);
return true;
}
catch (IOException)
{
return false;
}
}
myfile= new StreamWriter(myfiletowrite, true); //exception occurs here when I try to write to myfiletowrite which is currently open
I am unsure on how to close this file which is open in the background so I could write to this file. I would appreciate it someone could help me with this.
If the other application did not explicitely allow it (via Share mode), it is not possible to open the file for writing.
If the other application is under your control, you have some options (open the file with FileShare.Write, implement some communication protocol between the two applications, use a common service for accessing the file, ...).
Best option would be to choose a different file name.

c# Fill a richTextBox with Microsoft Word or Wordpad

I have a question.
I have a winform with a richTextBox1, this textbox is readonly, but there is a "Edit"-Button. When you press the Edit-Button, Wordpad or maybe Microsoft Office will open, then you write a Text in the Office tool and after you close word/wordpad, the richTextBox1 will be filled with the Text from the Wordpad.
Is this possible? and if Yes, how ?
It is very simple:
private void btnEdit_Click(object sender, EventArgs e)
{
var myFileName = #"myRtb.rtf";
//Save your RichTextBox text to a file.
richTextBox1.SaveFile(myFileName);
string PathToApp = #"Microsoft Office Word 2007.lnk";
//Make a System.Diagnostics.Process object
Process runProg = new Process();
try
{
//With path to your MS Office application
runProg.StartInfo.FileName = PathToApp;
//Command line arguments to open file
runProg.StartInfo.Arguments = "/t" +" "+ myFileName;
runProg.StartInfo.CreateNoWindow = true;
//And start your application and also open file
runProg.Start();
}
catch (Exception ex)
{
}
}
A documentation to Microsoft Office products command line arguments:
https://support.office.com/en-us/article/Command-line-switches-for-Microsoft-Office-products-079164CD-4EF5-4178-B235-441737DEB3A6
I might have an answer.
Start up Word with a parameter for the desired file location. Then edit your file and save it. When your app detects that Word has closed or the file has been created, whichever, then you can load that word file into your textbox.
It's a little more long winded than that I'm sure, but that's the gist, totally possible.
I'd begin by looking into Aspose, a library for Microsoft products that exposes simple APIs to use.
Good luck!

Is it possible to save a word document by bypassing the Save or SaveAs methods c#

I have a MS Word AddIn that launches a winform which allows the user to specify some additional metadata which is then saved as an xml file along with a copy of the document in a specified location.
This all works fine when run from a standalone Word document, however one of the areas this will be used is where a Word document is launched inside an application (EMIS WEB). It launches a copy of Word from the local machine which is fine as it allows the AddIn to be run.
When I try to save the document I get a Command Failed. error. The XML file saves no problem: xml.Save(path + docName + ".xml");.
The application prompts with it's own 'save' like dialog.
At first I thought it was the application removing focus from the document therefore this.Application.ActiveDocument.SaveAs failing because it wasn't the Active Document. So I tried getting the Document object when it was active and passing it through to the saveDoc method so that I could set it as the Active Document like so:
public void saveDoc(string doc, Word.Document wd)
{
string path = #"\\servername\folder\subfolder\";
object filename = path + doc + ".docx";
try
{
wd.Activate();
this.Application.ActiveDocument.SaveAs(ref filename);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
However this made no difference, the application's dialog still pops up, and regardless of whether I click OK or Cancel to the dialog it does not process the SaveAs command.
I have come to the conclusion that the application is intercepting the Save/SaveAs command and doing its own thing instead.
So is it possible to save a word document by bypassing the Save or SaveAs methods? Is there a way round this?
Figured it out, fortunately there was not a strict requirement to save it as a .doc or .docx so I have opted for .pdf. I have got round the application intercepting the Save commands by using the Document.ExportAsFixedFormat Method with wdExportFormatPDF to save it as a PDF.
So the final code looks like this, and it works a treat:
public void saveDoc(string doc)
{
string path = #"\\servername\folder\sub-folder\";
string filename = path + doc + ".pdf";
try
{
this.Application.ActiveDocument.ExportAsFixedFormat(filename, WdExportFormat.wdExportFormatPDF);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}

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.

SaveCopyAs method does not work

(I'm week in English language, so at first excuse me for bad explaining :D )
I open an excel file through my application.
I have an Addd-In in Excel and a button in ribbon for save (exactly such a save action that Save button do) code of Click event of button is here:
Globals.ThisAddIn.Application.ActiveWorkbook.Save();
In my application I assign a method (called WorkbookBeforeSave) to "BeforeSave" event handler of workbook that save workbook manually in my custom directory.
private void WorkbookBeforeSave(bool saveasui, ref bool cancel)
{
_excelApp.EnableEvents = false;//_excelApp is my Excel Application
if (!_excelWorkbook.Saved)//_excelWorkbook is Active Excel Workbook
{
_excelWorkbook.SaveCopyAs(_savedFilePath);//_savedFilePath is my custom directory
_excelWorkbook.Saved = true;
}
cancel = true;
_excelApp.EnableEvents = true;
}
problem is when I click Original Excel Save Button "SaveCopyAs" method works correctly but when click on my custom Save Button "SaveCopyAs" method does not work.
(no exception has thrown and all of codes compiled and debugged)
Try to debug with try-catch, it should be helpful for you.
// using interop, excel tool, interop-excel, core
public void MyBeforeSave(Microsoft.Office.Interop.Excel.Workbook Wb, bool SaveAsUI, ref bool Cancel)
{
//Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs(filename2); // if u use an external class to save (for threading or something else )
this.Application.ActiveWorkbook.SaveCopyAs(filename);
}
Without threading/tasking the office 2007 excel - sometime - lagging or slower than normal at loading and at the save method.
The simple saveAs() method have lot of parameters (searh for it, you see it on msdn & here too) and its needs some hoak at the path, because the latest save-path change to the C# used save path.
I prefer the SaveCopyAs solution, because just one parameter and fast & furious. :D

Categories

Resources