how to identify that a worksheet is minimized? - c#

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

Related

Returning Excel variables C#

I have a Windows Forms application with 5 methods (each based off of the user clicking a button). In each method, I would like to open the same excel file the same way. However, in each method I want to select a different range on the worksheet. I tried creating a function to open the excel file rather than rewriting it 5 times...
// method to open Excel and load a the workbook based on date selected.
public Tuple<Microsoft.Office.Interop.Excel.Application, Workbook, Worksheet> openExcel()
{
Microsoft.Office.Interop.Excel.Application excelObj = new Microsoft.Office.Interop.Excel.Application();
string fileName = #"C:\Users\" + userName + #"\Documents\Visual Studio 2015\Projects\ProgramForMom\ProgramForMom\bin\Debug\Excel Files\" + frm2.year.Text + " Expenses";
Workbook wb = excelObj.Workbooks.Open(fileName, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
wb.Activate(); // Activates file.
Worksheet ws = wb.Worksheets[frm2.month.Text];
ws.Activate();
return Tuple.Create(excelObj, wb, ws);
}
All that works fine.
I tried referenced this function in one of the methods...
var excelObj = openExcel();
Workbook wb = openExcel();
Worksheet ws = openExcel();
var cellValue = ws.Range["A1"].Value2;
and I get an error saying...
"Cannot implicitly convert type 'System.Tuple' to 'Microsoft.Office.Interop.Excel.Workbook'. An explicit conversion exists (are you missing a cast?)"
I get the same error for the worksheet. It says the same exact thing just substitutes the word worksheet in place of workbook.
Can you please explain what I have done wrong? Thank you.
var result = openExcel();
var excelObj = result.Item1;
Workbook wb = result.Item2;
Worksheet ws = result.Item3;
var cellValue = ws.Range["A1"].Value2;
You have a mismatch between the return type of your method (which is a Tuple) and the type of the variables in which you want to catch the output of openExcel
it should look more like this
Tuple<Microsoft.Office.Interop.Excel.Application, Workbook, Worksheet> allThreeInOne = openExcell();
then you can try and fiddle everything apart... OR
what you also can do is to access the value right at the point of the function call:
var excelObj = openExcel().Item1;
Workbook wb = openExcel().Item2;
Worksheet ws = openExcel().Item3;
this way you would assign exactly the matching type to the variables
EDIT:
Tha latter solution is not advisable since you would unnecessarily open the file 3 times just to get the result that you would have gotten already from the first call,as Joel Coehoorn correctly pointed out.
fiddling the tuple apart would be the way to go:
var excelObj = allThreeInOne.Item1;
Workbook wb = allThreeInOne.Item2;
Worksheet ws = allThreeInOne.Item3;

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 read the value from excel in c# without using third party dll?

I have a excel file which is named strings.xls in C:
Excel.Application excelApp = new Excel.Application();
string workbookPath = "c:/strings.xls";
Excel.Workbook excelWorkbook = null;
try
{
excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0,
false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
}
catch
{
excelWorkbook = excelApp.Workbooks.Add();
}
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1";
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("A1", "A1");
excelCell.Value2 = "Hi There";
You can't.
Since this is XLS file (a binary format), the simplest solution would be to use Excel (Microsoft Jet) OLE DB driver to retrieve that value. Example
If you can change the process to provide XLSX files then you could open then in plain .NET and parse the values out of the XML files.
You can use Jet OLE DB Provider With Microsoft Excel Workbooks to read values from excel. This is good codeproject article with example code for oledb with excel.
You can also use do it using Microsoft.Office.Interop.Excel, this codeproject article would be good starting point.
You can connect to an Excel file using OLE DB provider.
Have a look at this example.

Categories