Change ActiveWorkbook When Multiple Instances Open - c#

I am opening an Excel file, and if it does not meet certain conditions, I am then creating a new workbook. Problem I am having is that when the new workbook is created it is not by default set to the activeworkbookso when I try to use activeworkbook.saveas()it saves the 1st workbook, with inaccurate data.
This is what I am using to create the new workbook:
Excel.Workbook newWorkbook = this.Application.Workbooks.Add();
Can someone show me how to change activeworkbook in Excel when multiple workbooks are opened?
BTW this is Excel 2007 I am working with.
Copy worksheet to new workbook
ws = wb.Sheets["Mitchell"];
((Excel.Worksheet)ws).Copy();

Configuration Details:
Code is written in vb.net using Visual Studio 2010 Professional
All example code is placed in the ThisAddIn_Startup event handler of the
Application-Level Add-In for Excel 2010
In project references (right click project > properties >
references) make sure there is a check beside Excel = Microsoft.Office.Interop.Excel
When multiple worksheets are open, I use For Each to loop through the collection and see the names...
For Each wrkbk As Excel.Workbook In Me.Application.Workbooks
MsgBox(wrkbk.Name)
Next
Combine this with a Select Case and this allows you get at any workbook that is open.
For Each wrkbk As Excel.Workbook In Me.Application.Workbooks
Select Case wrkbk.Name
Case "Book1"
wrkbk.Activate()
Case "Book2"
Case Else
End Select
Next
Now, tying it all together, you can do this:
Create a new workbook named CustomWorkbook.xlsx
Activate Book1, copy Sheet1, and paste it into CustomWorkbook.xlsx (rename sheet to CopiedWorksheet)
Activate CustomWorkbook.xlxs
//Hide alerts so no prompts display when using SaveAs to rename new workbook
Me.Application.DisplayAlerts = False
//Programatically create a new workbook
Dim myWrkbk As Excel.Workbook
myWrkbk = Me.Application.Workbooks.Add()
//Name new workbook
myWrkbk.SaveAs("CustomWorkbook")
//Set Book1 as the active workbook (so can copy sheet)
Application.Workbooks("Book1").Activate()
//Create a new worksheet variable
Dim sourceWrksht As Excel.Worksheet
sourceWrksht = Application.Worksheets("Sheet1")
sourceWrksht.Range("A1").Value = "Text in a Cell"
//Select Sheet1 and copy into CustomWorkbook and paste as first sheet
sourceWrksht.Select()
sourceWrksht.Copy(Before:=Application.Workbooks("CustomWorkbook.xlsx").Sheets(1))
//Rename copied worksheet
Dim destinationWrksht As Excel.Worksheet
destinationWrksht = Application.Workbooks("CustomWorkbook.xlsx").Sheets(1)
destinationWrksht.Name = "CopiedWorksheet"
//Loop through all open workbooks in Excel Application
For Each wrkbk As Excel.Workbook In Me.Application.Workbooks
Select Case wrkbk.Name
Case "CustomWorkbook.xlsx"
wrkbk.Activate()
Case "Book1"
Case Else
End Select
Next
//Set Excel to show alerts again
Me.Application.DisplayAlerts = True

Simply call the Activate() method on the workbook you want to show.
When you create a new workbook you could use this:
Excel.Wokrbook oldWorkbook = this.Application.ActiveWorkbook;
Excel.Workbook newWorkbook = this.Application.Workbooks.Add();
oldWorkbook.Activate();
And after a while:
newWorkbook.Activate();
See the docs at MSDN.
Except:
The Activate method of the Workbooks collection activates a Microsoft Office Excel workbook and selects the first sheet in the workbook.
EDIT:
This works for me:
Excel.Workbook oldWorkbook = this.Application.ActiveWorkbook;
this.Application.ActiveWorkbook.Sheets["name"].Copy();
Excel.Workbook newWorkbook = this.Application.ActiveWorkbook;
old = Book1
new = Book2

Related

Excel Interop set View style of worksheet to a normal view

How do I change the view style of Excel Worksheet In Excel interop to a Normal style?
Like this:
Just have no idea :(
Does someone know?
i see just one solution, you have to use ActiveWindow.View: a sample to use it
using Excel = Microsoft.Office.Interop.Excel;
object missing = System.Reflection.Missing.Value;
Excel.Application excel = new Excel.Application();
Excel.Workbooks wbs = excel.Workbooks;
Excel.Workbook wb = wbs.Open(#"d:\test.xlsm");
Excel.Worksheet sheet = wb.ActiveSheet;
// set the view style
excel.ActiveWindow.View = XlWindowView.xlNormalView;
object filename = #"d:\test1.xlsm";
wb.SaveAs(filename);
wbs.Close();
excel.Quit();
if you have more Worksheets, you have to do that on each Worksheet...

C# set opened workbook

I started creating an Excel-Add-IN with C#.
what I need to do is simple, I need to set a workbook to a variable, the workbook is already running, I tried this but did not work
Excel.Application excel = new Excel.Application();
Excel.Workbook wb = excel.ActiveWorkbook as Excel.Workbook;
wb.SaveAs("C:\\Users\\ro_sg\\Desktop\\Pasta1.xlsx");
Excel.Worksheet ws = wb.Worksheets["Plan1"];
Excel.Range range = ws.Range["A1"];
range.Value = "Success";
wb.Save();
The wb variable cannot find the workbook (gets null), and I can't see why.
Please, if any of you spot the mistake let me know.
Thanks!
I believe your issue is it may not be finding the active Excel application upstream from when you set your workbook variable. It appears that your code is trying to create a new excel application (without a workbook) rather than get the existing one that is open.
Give this a try:
Excel.Application excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
Excel.Workbook wb = (Excel.Workbook)excel.ActiveWorkbook;
wb.SaveAs("D:\\WeeeDueceDuece.xlsx");
I don't know if you need to get a specific Sheet but if you try this: Excel.Worksheet ws = wb.Worksheets[1]; It will get the first Sheet of your Workbook
If your actual code doesn't have more in-between steps, it will always fail. I'm surprised this line didn't error:
Excel.Workbook wb = excel.ActiveWorkbook as Excel.Workbook;
It's because a new instance of Excel does not necessarily create a new workbook. You can check this with the following lines:
Excel.Application application = new Excel.Application();
Excel.Workbooks workbooks = application.Workbooks;
Console.WriteLine(workbooks.Count); // "0"
The new workbook, however, should create the default number of worksheets (usually 3, but editable).

Find and edit open Excel sheet using interop

I have linked an application that gets data from an API, I open the sheet when a new contract is loaded to the program. Now I am trying to write new data to the excel sheet later in the program when i collect new data.
I know how to write data to the excel sheet and how to open the sheet I want to write on. The problem is I don't know how to write to the sheet once its already open, all I can get it to do is open another instance of the sheet.
I need to be able to open the sheet in one void and then update the now open sheet in a later void. How do I check to see if the sheet is open and if it is then access it again to write more data to it?
Here is how I have opened Excel,
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Console.WriteLine("Opening Excel...");
if (xlApp == null)
{
Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
return;
}
xlApp.Visible = true;
Workbook wb = xlApp.Workbooks.Open(#"C:\Users\Craig Key\Desktop\AppExports\TestExport.xlsx");
Console.WriteLine("Opening Currently Linked Workbook...");
Worksheet ws = (Worksheet)wb.ActiveSheet;
Console.WriteLine("Opening Active Worksheet...");
if (ws == null)
{
Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct.");
}
Now later I need to find xlApp later in the program and write to it again, without opening another instance of the file.
I figured this out after searching for a while, I needed to use the marsh to try to bind the the open instance and then work with it.
Microsoft.Office.Interop.Excel.Application xlApp = null;
//Microsoft.Office.Interop.Excel.Workbooks wbs = null;
Microsoft.Office.Interop.Excel.Workbook wb = null;
Microsoft.Office.Interop.Excel.Worksheet ws = null;
bool wasFoundRunning = false;
Microsoft.Office.Interop.Excel.Application tApp = null;
//Checks to see if excel is opened
Console.WriteLine("CDC is looking for Excel...");
try
{
tApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
wasFoundRunning = true;
}
catch (Exception)//Excel not open
{
wasFoundRunning = false;
}
if (true == wasFoundRunning)
{
//Control Excel
}

How to output Excel.workbook content into existing Excel file from C# application?

I have a macro-enabled Excel file "D:\MyTests\ExcelTests\template.xlsm" with no data in it, only the VBA code, and my C# code needs to output a workbook data over there. Normally I output workbook data like this:
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
Excel.Worksheet worksheet2 = workbook.Sheets[2];
// populate worksheets with some data
DataTable2Worksheet(tableMain, worksheet, verSize);
DataTable2Worksheet(tableExtra, worksheet2, 0);
string fileName = #"D:\MyTests\ExcelTests\newFile";
if (File.Exists(fileName ))
{
File.Delete(fileName );
}
workbook.SaveAs(fileName);
workbook.Close();
Marshal.ReleaseComObject(application);
but this creates a new file (which cannot be macros enabled programmatically). If I want to output the workbook to existing file
string existingFile = #"D:\MyTests\ExcelTests\template.xlsm"
the method
workbook.SaveAs(existingFile );
won't work. So, what should I do instead? Thanks.
Save the file specifically in xlOpenXMLWorkbookMacroEnabled format:
string existingFile = #"D:\MyTests\ExcelTests\template.xlsm"
workbook.SaveAs(existingFile, 52);

C# Excel 2010 programing

I am writing a program in C# for analysing a structure details in an earth quake.I have a lot of data and want to put them in a excel file.
I mean i need a function like this :
public void excel(int sheet_no,int row,int column,string value)
Is there any way to parse the text file and Put this data in Excel sheet ?
use this :
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Workbooks workbooks;
_Workbook workbook;
_Workbook workbook2;
Sheets sheets;
_Worksheet worksheet;
app.Visible = false;
workbooks = app.Workbooks;
workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
sheets = workbook.Worksheets;
worksheet = (_Worksheet)sheets.get_Item(1);
worksheet.Cells[row, column] = value;
workbook.Saved = true;
workbook.SaveAs(output_file);
app.UserControl = false;
app.Quit();
Take a look at ClosedXml
Code sample:
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");
But if you are dealing with a lot of data, consider using a database like sqlserver.
It provides a lot of analysis tools.
You can connect it as a datasource to excel too.
For now, I am providing links for you to read # Excel Tasks and code samples # Excel controls in ASP.net. If you're still confused, I may be able to find code samples from my projects or the Internet, which are not hard to find.
Look at link Workbook Open (create) method to create Workbooks, and link Workbook Open method to open Workbooks.

Categories

Resources