excel object returns count zero Please refer the screenshot.
I need to access objects of file type PPT, Excel, Word which are opened through an application similar to sharepoint.
While I try getting count of opened excel files I always get the count as 0. I already searched if I can get help, got to see this Accessing an open Excel Workbook in C# but though implementing the solution it returns 0.
Microsoft.Office.Interop.Excel.Application xlObj =
(Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
while (xlObj.Windows.Count == 0) // This line returns the count as 0
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"C:\Users\nagendra.k.kumar\Desktop\Talent Review - Nagendra Kumar.xlsx");
Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range xlRange = lWorksheet.UsedRange;
MessageBox.Show(xlRange.Rows.Count.ToString());
Related
I wrote a program in C# that is supposed to convert each worksheet in my excel workbook to a csv and save it in their own files. The problem I'm having is that when I open each file, they all have the same content as the very last worksheet. Here is my code:
public void Main()
{
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Open(#"C:\Users\user\Desktop\Book1.xlsx");
foreach (Excel.Worksheet sht in workbook.Worksheets)
{
sht.Select();
System.Diagnostics.Debug.WriteLine(sht.Name.ToString());
workbook.SaveAs(string.Format("{0}{1}.csv", #"C:\Users\user\Desktop\", sht.Name), Excel.XlFileFormat.xlCSV, Excel.XlSaveAsAccessMode.xlNoChange);
}
workbook.Close(false);
Dts.TaskResult = (int)ScriptResults.Success;
}
Any help would be great, thanks!
Update 1
I don't know if it's worth mentioning that I'm trying to do this through a script task in SSIS. So it's just one script task that I run that contains the code above.
Trying to figure out the issue
In normal cases, the code you provided will work perfectly. It may encounter some issue in case that the excel application has shown a message box, need permissions to enable editing, there are permissions issue to access other worksheets since they are protected ...
First of all, open the excel manually and check that you can access all worksheets and perform save operations manually. If you didn't encountered any issue, then you should prevent excel from showing message boxes or other promotion while using Interop.Excel library.
In addition, check that the Csv does not already exists in the destination path.
Try using a similar code:
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = false;
excelApp.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook workbook = excelApp.Workbooks.Open(#"D:\Book1.xlsx");
workbook.DoNotPromptForConvert = true;
workbook.CheckCompatibility = false;
foreach (Microsoft.Office.Interop.Excel.Worksheet sht in workbook.Worksheets)
{
sht.Select();
System.Diagnostics.Debug.WriteLine(sht.Name.ToString());
if (System.IO.File.Exists(string.Format("{0}{1}.csv", #"D:\", sht.Name)))
{
System.IO.File.Delete(string.Format("{0}{1}.csv", #"D:\", sht.Name);
}
workbook.SaveAs(string.Format("{0}{1}.csv", #"D:\", sht.Name),
Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange);
}
//workbook.Close(false);
workbook.Close(false, Type.Missing, Type.Missing);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
I tested the following code and it converted all Worksheets successfully.
Here I'm opening excel and writing to excel sheet. I'm changing my windows application to asp website and seen this error. I have added all the references and libraries. Don't know what I am missing here.
Getting error as mentioned below. Please help me.
Excel.Application excel = new Excel.Application();
excel.Visible = false; // to hide the processing
Excel.Workbook wb = excel.Workbooks.Add();
Excel.Worksheet sh = wb.Sheets.Add(); // Error at wb
sh.Name = "Links";
for (int i = 1; i < list.Count; i++)
{
sh.Cells[i.ToString(), "A"].Value2 = list[i]; //Error at .Value2
}
you have to create a new Worksheet with Sheets array by providing WorkSheet Name.
and also please Cast The Newly Created WorkSheet.
Replace this :
Excel.Worksheet sh = wb.Sheets.Add();
with following
Excel.Worksheet sh = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets["Sheet1"];
To resolve your second error,
//Error at .Value2
Go to project properties. (Click Project in Menu, Click properties)
Set the Target Framework as .NET Framework 4
This should resolve your .Value2 error.
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).
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
I am getting error while using the Excel Interops set_Value on a range.
Any help/suggestion will be valuable.
This is the code which is failing.
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.ApplicationClass();
Excel.WorkBook WB = xlApp.Workbooks.Add(Type.Missing);
Excel.WorkSheet WS = WB.Sheets[1] as Excel.WorkSheet;
object obj = (WS.get_Range("A1:D10") as Excel.Range).get_Value(Excel.XLRangeValueDataType.XLRangeValueMSPersistXML);
(WS.get_Range("A1:D10") as Excel.Range).set_Value(Excel.XLRangeValueDataType.XLRangeValueMSPersistXML,obj);
The code fails here.
I am setting the same object value which i am getting from excel range.
The exception shown is System.NotImplementedException.
I am clueless at this point if it is the office interop doesn't support XLRangeValueMSPersistXML while setting the value back to the excel range.
When setting the value, it appears that you should leave off the RangeValueDataType setting. The following code does not cause the NotImplementedException to be thrown. (It also corrects some case problems that prevent your original sample from compiling, as well as tidying it up a bit.)
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.ApplicationClass();
Excel.Workbook WB = xlApp.Workbooks.Add(Type.Missing);
Excel.Worksheet WS = WB.Sheets[1] as Excel.Worksheet;
Excel.Range r = WS.Range["A1:D10"];
var obj = r.Value[Excel.XlRangeValueDataType.xlRangeValueMSPersistXML];
r.Value = obj;