How to open an Excel file in PrintPreview without suspending the code - c#

I'm new to C#/OpenXML and could not find an answer to this. Apologies in advance if it's a stupid question...
Basically, I am writing an application that creates Excel files from an input string. This input string may contain information about multiple files that need to be created and opened in the print preview dialog simultaneously. However, using the following function, the code is suspended on the printpreview.show() method as it waits for the user to close the preview.
public static void ExcelOpen(string fileName)
{
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(fileName, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, false, 0, false, false);
Excel.Worksheet ws = (Excel.Worksheet)excelWorkbook.Worksheets[1];
excelApp.Dialogs[Excel.XlBuiltInDialog.xlDialogPrintPreview].Show();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
return;
}
How can I avoid this and make sure the window stays opened in print preview but my program continues to run and create/display further files?

Related

Unable to change link in Excel workbook

I'm having problems changing a link in a workbook that contains a moved sheet.
I move two worksheets from a workbook (tempworkbook) called "Analysis Template.xlsx" into a new workbook (_wb), at which point, I then want to change the link that's in those two sheets from tempworkbook to refer to the new workbook they've just been moved into, yet my changelink code seems to have no effect, and i'm positive i've got the paths correct. Why is this? It's not returning any error, it's just when I check the link in excel itself, its still pointing to the original "Analysis Template" workbook.
As I want this to run in the background, i've disabled a few things within the application, could this be why?
_xl.Visible = false;
_xl.UserControl = true;
_xl.DisplayAlerts = false;
_xl.Interactive = false;
_xl.ScreenUpdating = false;
Microsoft.Office.Interop.Excel.Workbook tempworkbook = _xl.Workbooks.Open(System.IO.Directory.GetCurrentDirectory() + "\\Analysis Template.xlsx", 0, false, 1, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, 9, true, false, 0, true, false, false); //open template XLS file
Microsoft.Office.Interop.Excel.Worksheet tmp1 = (Microsoft.Office.Interop.Excel.Worksheet)tempworkbook.Sheets["Data"]; //extract 1st worksheet to move
Microsoft.Office.Interop.Excel.Worksheet tmp2 = (Microsoft.Office.Interop.Excel.Worksheet)tempworkbook.Sheets["Evaluation"]; //extract 2nd worksheet to move
tmp1.Move(Missing.Value, _wb.Sheets[7]); //move 1st worksheet into new workbook
tmp2.Move(Missing.Value, _wb.Sheets[8]); //move 2nd worksheet into new workbook
_wb.ChangeLink(tempworkbook.FullName, _wb.FullName, Microsoft.Office.Interop.Excel.XlLinkType.xlLinkTypeExcelLinks); //change link from template workbook to refer to new workbook
The documentation suggests that you probably need to do a loop over all link sources, and update them each individually.
If you were looking to debug the problem, I would strongly suggest you at least confirm that tempworkbook.FullName is the same as the output of LinkSources(_wb).
Haven't done it personally, just trying to help.

Load an Excel file using implicit typing

class ExcelHandling
{
public static void NewExcelFile(){
frmMain._frmMain.EXCEL_FILE = new Excel.Application();
var excelApp = frmMain._frmMain.EXCEL_FILE as Excel.Application;
excelApp.Workbooks.Add();
excelApp.Visible = true;
}
public static void LoadExcelFile()
{
FileStream load = File.Open(#"F:\dsa.xlsx", FileMode.Open, FileAccess.Write);
var excelApp = load as Excel.Application;
frmMain._frmMain.EXCEL_FILE = excelApp;
excelApp.Visible = true;
}
}
The above shown LoadExcelFile() method doesn't work.
What is the correct way of loading an existing excel file into a variable? I've tried a few things, but to no avail. The NewExcelFile() method works like a charm - it creates a new Excel file, stores it into the EXCEL_FILE global variable so I can manipulate it thereafter and shows it. I want the load function to do the same but with an existing excel file.
Here is an example of opening an existing Excel spreadsheet using the Microsoft.Interop library:
var xlApp = new Microsoft.Office.Interop.Excel.Application();
var xlWorkBook = xlApp.Workbooks.Open("PathAndNameOfMyFile.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
The overload parameters are fairly vague in documentation, but unfortunately required. Intellisense should give you some idea of the values and their meaning.
Your issue was that you were using a FileStream and then trying to let the library figure out what that stream contained. This will utilize the interop library to open the file and handle the data properly.
I really like LinqToExcel. You can use NuGet Package Mgr in Visual Studio to add it https://www.nuget.org/packages/LinqToExcel . Documentation is #https://code.google.com/p/linqtoexcel/ (with a demo video)

How to edit the data of an excel worksheet without affecting the other worksheets?

Suppose I have an excel file containing 4 sheets, Sheet 1, Sheet 2 and so on. I need to read data from a List object, truncate all the data of Sheet 1, and write the data from the List object into that Sheet 1, without affecting any other sheet..
This is what I have been trying..
string pathFileSource = "C:\\Temp\\Output.xls";
string pathFileDestination = "C:\\Temp\\Performance Testing.xls";
Excel.Application excel = new Excel.Application();
Excel.Workbook wbSource = excel.Workbooks.Open(pathFileSource, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Workbook wbDestination = excel.Workbooks.Open(pathFileDestination, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Worksheet WorksheetSource = wbSource.Sheets[1];
//Copy all range in this worksheet
WorksheetSource.UsedRange.Copy(Missing.Value);
Excel.Worksheet WorksheetDestination = wbDestination.Sheets[1];
// Select used Range, paste value only
WorksheetDestination.UsedRange.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationAdd, false, false);
wbSource.Close();
wbDestination.Save();
wbDestination.Close();
//Quit application
excel.Quit();
Although I am getting alerts stating that the data has been added to Clipboard, the destination file is not getting updated with the correct data. Any pointers as to where I am going wrong?
I will be really grateful if someone can provide an actual working code, and not pseudocodes.
This is (default)normal mode of MS Excel to edit one worksheet at a time and separately or independently of other worksheets.
However, if you have created a Worksheet Group by selecting worksheet tabs, then first of all, you have to un-group the worksheets. Then you can handle every worksheet independently.
I hope this may help!
You can make a Group of worksheets by:
Press and hold CTRL key and click on worksheet tabs(left button click).
And un-group your worksheets by the same process again.

how to identify that a worksheet is minimized?

How to identify the current active worksheet is minimized ?
I do not want to run my operation when the current worksheet in excel is minimized. I am using excel interop and C#
You can do a conditional check on the following property,
If Application.WindowState = xlMinimized Then
// do something
End If
This is in VBA though.
Here is a basic code in C#
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application myXL = new Excel.Application();
myXL.Visible = true;
//adding a new book
Excel.Workbook xlBookN = myXL.Workbooks.Add();
//opening exising book
String xlPath = "c:/myprojects/test.xls";
Excel.Workbook xlBookE = myXL.Workbooks.Open(xlPath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Dim myWindowState As XlWindowState //you could also use a variable
myXL.WindowState = myWindowState
//or you can check the state directly
If (myXL.WindowState = xlMinimized)
// do something
End If
Please check on the syntax and references.
You could get better reference from :
MSDN
MSDN OFFICE INTEROP

C# Excel Interop: Opening and Showing CSV file

Hey I'm writing a wrapper for the excel interop, I want to be able to open a csv file in excel and show it to the user. I've got the basics down, but when i set visible to true and excel shows up, all columns are jammed into the first, and the separating commas are showing.
here's my helper.
public MyExcel(string filePath, bool readOnly)
{
_app = new Excel.Application();
_workbooks = _app.Workbooks;
_workbook = _workbooks.Open(_filepath, 0, _readOnly, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", !_readOnly, false, 0, true, true, true);
}
public void Show()
{
_app.Visible = true;
}
any suggestions?
When i open the file by double clicking Excel processes everything properly.
You will need to use the OpenText method, instead of Open, if you want Excel to parse for delimiters. Details: http://msdn.microsoft.com/en-us/library/bb223513%28v=office.12%29.aspx
An example in C#: http://msdn.microsoft.com/en-us/library/c9838808.aspx
It is MUCH easier than that if all you want to do is open the file...
Process proc = new Process();
proc.StartInfo = new ProcessStartInfo("excel.exe", "output.csv");
proc.Start();

Categories