why does openfiledialog cause excel to be added to task manager processes? - c#

why does this cause an occurrence of excel to be open?
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
//EXCEL.EXE *32 is now showing in the task manager!
i am choosing an XLSX file from the openfiledialog and as shown above i am seeing the process in the task manager.
can someone please tell me how is this possible?

If Excel is already open, you should try to get this instance, instead of creating a new one.
using System.Runtime.InteropServices;
...
Excel.Application xl = null;
try {
// Try to get an existing instance
xl = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
} catch (COMException ex) {
// Excel was not open. Open a new instance
xl = new Excel.ApplicationClass();
}

Related

Check if a specific word document is Open using c#

Is there any way to check if a specific word document is Open? When I open document myself before opening the app when I tell to my app to write something in document first try to open the document and thats where my app is stuck.Is there a way to check before I try to open if the file is already opened? at this moment my code looks like this:
object filename = s; // s is a string path which I get from database
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc1 = app.Documents.Open(s);
object missing = System.Reflection.Missing.Value;
app.Visible = true;
just put your code in a
try
{
//your code here
}
catch (Exception e)
{
//your behavior when the file is opened
}

Opening Excel workbook via code vs dbl clicking

I have an excel file that runs some simulation. It's too complex to post here but it's also not the thing really in question, but what I'm seeing is that if I just dbl click the workbook to open it and then run the simulation (click a button on the workbook) it works fine. However if I use the below code in a C# project to open the workbook and then run the simulation (again just click the button) it gives different results. I'm wondering if anyone knows anything about why anything would be different when you open a workbook via code vs just dbl clicking it to open. I'm completely at a loss and any ideas at all would help a ton. Thanks!
private Application oExcel = null;
private Workbooks oBooks = null;
private _Workbook oBook = null;
private void OpenExcelFile(string filename)
{
oExcel = new Application();
oExcel.Visible = true;
oExcel.DisplayAlerts = false;
//oExcel.DisplayAlerts = true;
oBooks = oExcel.Workbooks;
oBook = oBooks.Open(filename);
}
I've tried both Microsoft Excel 14.0 and 15.0 Object Library

Save excel file using savefiledialog class in C#

I need to create and save a Excel file without inform in the code the path and file name. So I can use the savefiledialog to show the save box to input the path and file name, but I can´t use it correctly.
I tried to use the worksheet.saveas but this class doesn´t show the save box to input the path and file name.
How can I save a excel file with that save box?
The basic mechanic of it is this:
public void SaveExcelWorkBook()
{
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.InitialDirectory = #"C:\";
openDlg.ShowDialog();
string path = openDlg.FileName;
if (openDlg.ShowDialog() == DialogResult.OK)
{
try
{
Application excelApp = new Application();
Workbook workBook = excelApp.Workbooks.Open(path);
Worksheet workSheet = (Worksheet)workBook.Worksheets[1];
// Do your work here inbetween the declaration of your workbook/worksheet
// and the save action below.
workBook.SaveAs(/*path to save it to*/); // NOTE: You can use 'Save()' or 'SaveAs()'
workBook.Close();
}
catch (Exception ex)
{
}
}
}
I think I should also mention that Interop objects are unmanaged so, you will want to make sure that you are releasing them after calling .Close(). Here is an example:
Marshal.ReleaseComObject(workBook);
There are two fantastic tutorials for using Excel here and here. Good luck!

COMException on closing Excel workbook

I'm using Excel = Microsoft.Office.Interop.Excel to write various data to Excel sheets.
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
try {
// Create new workbook
wb = (Excel.Workbook)(excelApp.Workbooks.Add(Type.Missing));
ws = wb.ActiveSheet as Excel.Worksheet;
// write data ...
// Save & Close
excelApp.DisplayAlerts = false; // Don't show file dialog for overwrite
wb.Close(true, targetFilename, Type.Missing);
} finally {
// Close the Excel process
if (null != ws)
Marshal.ReleaseComObject(ws);
if (null != wb)
Marshal.ReleaseComObject(wb);
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
GC.Collect();
}
This code is exectued by multiple threads at a time, and it's been working almost always. Even the Excel processes disappear in task manager.
However, sometimes a System.Runtime.InteropServices.COMException is thrown at wb.Close(true, targetFilename, Type.Missing). It claims that access on the target filename was denied. Though I've been making sure that the target filenames are unique.
May the exception be due to any bad handling of Excel or maybe that I'm using threads?
Apparently, targetFilename wasn't really unique. There was one single difference in upper/lower case spelling, and it seems like two threads tried to write to the same file at once. The issue was easily solvable by using targetFilename.ToLower().
Anyway, if you discover any further potential issues, please leave a comment.

Export xps to pdf in C#

I am a newbie and i want to generate PDF from Infragistics, Xamdatagrid. However as Infragistics doesnt provide this functionality ,i have generated XPS of Xamdatagrid and wants to convert that to XPS programitically. What are the possible work around and third party tool to do that?
If you export the xamDataGrid in an excel file then is pretty simple to use Excel.Interop and ask excel to export its workbook in PDF format
// Export an excel workbok in PDF format with landscape orientation
private static void ExportWorkbookToPDF(string workbook, string output)
{
Microsoft.Office.Interop.Excel.Application excelApplication =
new Microsoft.Office.Interop.Excel.Application();
excelApplication.ScreenUpdating = false;
excelApplication.DisplayAlerts = false;
excelApplication.Visible = false;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook =
excelApplication.Workbooks.Open(workbook);
if (excelWorkbook == null)
{
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
throw new NullReferenceException("Cannot create new excel workbook.");
}
try
{
((Microsoft.Office.Interop.Excel._Worksheet)excelWorkbook.ActiveSheet).PageSetup.Orientation =
Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;
excelWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, output);
}
finally
{
excelWorkbook.Close();
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
}
}
if you wish to create only pdf. then the simplest thing have any pdf printer on machine. One like PDF Creater and then just call the printing thing like below on the XamDataGrid.
make sure you select the PDF Printer on the Printer Selection Dialog Box.
// 1. Create Report object
Report reportObj = new Report();
// 2. Create EmbeddedVisualReportSection section.
// Put the grid you want to print as a parameter of section's constructor
EmbeddedVisualReportSection section = new EmbeddedVisualReportSection(xamdg);
// 3. Add created section to report's section collection
reportObj.Sections.Add(section);
// Optional. If you have progress indicator set its Report property to created report
// progressInfo.Report = reportObj;
// 4. Call print method
reportObj.Print(true, false);
You can also use thirdparty software like GhostXPS.
http://www.ghostscript.com/download/gxpsdnld.html
Just start the convert process with the correct arguments and it will generate the PDF for you. The drawback is that you have to save the files temporary to the disk and check the return code. Also make sure you are not violating the GNU license

Categories