C# Automating to Excel - c#

...
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
oXL = new Excel.Application();
oWB = (Excel._Workbook)oXL.ActiveWorkbook;
oSheet = (Excel._Worksheet)oWB.Sheets[1];
oSheet.Cells[5,10] = "Value";
...
yields this at crash:
Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
at ConsoleApplication1.Program.Main(String[] args) in C:\Wherever\Visual Studio 2008\Projects\ConsoleApplication20\ConsoleApplication20\Program.
cs:line 60
In this case, line 60 is
oSheet = (Excel._Worksheet)oWB.Sheets[1];
and the same thing happens if the line is written
oSheet = (Excel._Worksheet)oWB.ActiveSheet;.
Excel is already open onscreen at the time, with a fresh worksheet in place.

The error is telling you that oWB is null. It is null because unlike opening Excel from a GUI, automation does not create a new 3-sheet book. You need to specifically load a book first, or add one.
See example here http://support.microsoft.com/kb/302084 where it explicitly adds a new workbook to play with
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));

Related

Establish Connection to existing Excel Application and Run an Excel macro C#

All,
Apologies if this is a very basic question and has been asked before, I predominately write in VBA / JAVA. However a project I am working on requires a C# script. Which carries out 3 simple steps:
Target a excel workbook which is already open. File path:
\Csdatg04\psproject\Robot\Peoplesoft To LV\Master Files - Do not use\Transactions into LV Template.xlsm
Populate cells A1,A2 & A3 with three variables already retrieved earlier in the automation.
Run a macro stored within the filepath mentioned above Macro name "ControlMacroACT"
The code I have developed is below, however in each stage identified above I am encountering errors (Probably basic errors).
Error 1: This line of code is to open a workbook I would like this to target an already active workbook.
Error 2: Worksheet not found
public void RunActualsMacro(string Filepath, string Period, String FiscalYear)
{
//~~> Define your Excel Objects
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
//~~> Start Excel and open the workbook.
//Error 1
xlWorkBook = xlApp.Workbooks.Open("\\Csdatg04\\psproject\\Robot\\Peoplesoft To LV\\Master Files - Do not use\\Transactions into LV Template.xlsm");
// Populat Cells A1,A2,A3 with string variables
// Error 2 Worksheet not found
worksheet.Rows.Cells[1, 1] = Filepath;
worksheet.Rows.Cells[2, 1] = Period;
worksheet.Rows.Cells[3, 1] = FiscalYear;
//~~> Run the macro ControlMacroAct
xlApp.Run("ControlMacroACT");
//~~> Clean-up: Close the workbook
xlWorkBook.Close(false);
//~~> Quit the Excel Application
xlApp.Quit();
}
Any help would be much appreciated.
You need to use Marshal.GetActiveObject, and this code is roughly right, but cannot test right now.
public void RunActualsMacro(string Filepath, string Period, String FiscalYear)
{
//~~> Define your Excel Objects
Excel.Application xlApp = null;
Excel.Workbook xlWorkBook;
//~~> Start Excel and open the workbook.
//handle errors below
try {
xlApp = (Excel.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
} catch {
//perhaps exit - or throw??
}
xlWorkBook = xlApp.Workbooks["Transactions into LV Template.xlsm"];
// Populat Cells A1,A2,A3 with string variables
Excel.Worksheet ws = xlWorkBook.Worksheets["Sheet1"] //what the tab name of sheet
ws.Cells[1, 1] = Filepath;
ws.Cells[2, 1] = Period;
ws.Cells[3, 1] = FiscalYear;
//~~> Run the macro ControlMacroAct
xlApp.Run("ControlMacroACT");
//~~> Clean-up: Close the workbook
xlWorkBook.Close(false);
//~~> Quit the Excel Application
xlApp.Quit();
}

Excel sheet read only and C#

I'm trying to edit an Excel Sheet through C# code but the Excel sheet is giving me an error saying read only
CS0200 Property or indexer 'Range.Text' cannot be assigned to -- it is read only
This is the code that is trying to access the sheet.
Code:
//Load workbook
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"S:\Utils\documents\ServerManager\serverlist.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
xlWorksheet.Range["D2"].Text = "Kelly Cooper";
xlWorksheet.Range["D2"].Style.Font.FontName = "Arial Narrow";
xlWorksheet.Range["D2"].Style.Font.Color = Color.DarkBlue;
In the properties the Excel sheet is not read only and when I open it to edit it does not prompt me with the "This document is read only, want to enable editing." How can I go around this, Visual Studio won't let me compile because of it.
This is Excel in Office365.
You want to use .Value instead of .Text.
xlWorksheet.Range["D2"].Value = "Kelly Cooper";
xlWorksheet.Range["D2"].Style.Font.FontName = "Arial Narrow";
xlWorksheet.Range["D2"].Style.Font.Color = Color.DarkBlue;
If you check the documentation you can see that Text is read-only.
Also, if you check the documentation you can see that Value is not read-only.
EDIT
You also might have to change your Open parameters to:
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Filename: "path/to/file", ReadOnly: false);

Reading to an Excel file

I am trying to read an excel sheet using C# and store each row into an array. I am able to open the file but the code I am using currently reads to an "2D-Object" array but I would like to read the info into 1D-string arrays.
static void Main(string[] args)
{
// Reference to Excel Application.
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Path.GetFullPath("excelpractice1.xlsx"));
// Get the first worksheet.
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);
// Get the range of cells which has data.
Excel.Range xlRange = xlWorksheet.UsedRange;
// Get an object array of all of the cells in the worksheet with their values.
object[,] valueArray = (object[,])xlRange.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault);
// Close the Workbook.
xlWorkbook.Close(false);
// Relase COM Object by decrementing the reference count.
Marshal.ReleaseComObject(xlWorkbook);
// Close Excel application.
xlApp.Quit();
// Release COM object.
Marshal.FinalReleaseComObject(xlApp);
Console.ReadLine();
}
}
}
`
Sorry, I was trying to comment only. =X
But did it worked for you anyway? LinqToExcel is a great library for manipulate spreadsheets!
Please, let me know if has any doubt yet.
=)

Excel worksheet get item

I have a problem with Excel worksheet. I am trying to create an Excel file with c#.
This code works and runs correctly on my computer but in other computers get an error at last line:
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheetInvoice;
Excel.Worksheet xlWorkSheetInvoiceLine;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheetInvoice = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheetInvoiceLine = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
System.Runtime.InteropServices.COMException (0x8002000B): Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
at Microsoft.Office.Interop.Excel.Sheets.get_Item(Object Index)
I executed a sample application with similar code on a machine with Excel 2013 and it fails at the same line of code you mentioned. By default Excel 2013 application opens up with a single worksheet ("Sheet1") so you would have to modify the code accordingly
DISP_E_BADINDEX seems to suggest the number of worksheets is less on the other computers. Build in a check to see if the number of worksheets is less than 2 before using get_Item().
i have created new sheet and assigned xlWorkSheetInvoice and xlWorkSheetInvoiceLine to solve it.
var xlSheets = xlWorkBook.Sheets as Excel.Sheets;
var xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
var xlNewSheet2= (Excel.Worksheet)xlSheets.Add(xlSheets[2], Type.Missing, Type.Missing, Type.Missing);
xlWorkSheetInvoice = xlNewSheet;
xlWorkSheetInvoiceLine = xlNewSheet2;
xlWorkSheetInvoice = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheetInvoiceLine = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);

How can I open the current instance of Excel from my application?

How can I open my Excel worksheet in the current open instance of Microsoft Excel? When I use my code, a new instance of Excel is opened.
private Excel.Application xlApp;
private Excel.Workbook xlWorkBook;
private Excel.Worksheet xlWorkSheet;
xlApp = new Excel.Application();
xlApp.Visible = true;
xlWorkBook = xlApp.Workbooks.Open(textBox1.Text);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;
You can do something like the following to get a reference to a running Excel instance (if there is one):
public Excel.Application TryGetExistingExcelApplication()
{
try
{
object o = Marshal.GetActiveObject("Excel.Application");
return (Excel.Application)o;
}
catch (COMException)
{
// Probably there is no existing Excel instance running, return null
return null;
}
}
Once you have a reference to a running instance, you can access it's Workbooks collection.
One caveat: if you try to automate an existing Excel instance, you may get "server busy" exceptions. To avoid this, you can implement IOleMessageFilter error handlers. This article describes how to do it for automating Visual Studio; the technique is identical for automating Excel.

Categories