How to declare a Worksheet using a Script Task? - c#

I'm trying to declare a Worksheet to handle cells of .xlsx file, but my C# script fails when I declare Worksheet object :
Microsoft.Office.Interop.Excel.Application xlApp = new
Microsoft.Office.Interop.Excel.Application();
Workbook excelBook = xlApp.Workbooks.Open(fileFullPath);
MySheet = (Excel.Worksheet)excelBook.Worksheets[Data_Sheet];
I've tried all of this statements :
MySheet workSheet = (Worksheet)excelBook.Application.Sheets[1];
MySheet = (Excel.Worksheet)excelBook.Worksheets[1];
Even
Worksheet MySheet = new Worksheet();
MySheet = excelBook.Worksheets[Data_Sheet];
I'm using this code in a script task in SSIS package and it doesn't show me the error message, I have only the error window telling me that the contained scripts have error compilation.
Thank you for your help.

I really didn't understood if you are looking to add a new worksheet or just edit a current one. I will give some suggestions for both cases:
(1) Edit an existing Worksheet
If you are looking to edit an existing Worksheet, try one of the following:
(a) Using _Worksheet instead of Worksheet
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
As example:
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"file.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
For more information, check to following links:
Read Excel File in C#
Reading data from excel 2010 using Microsoft.Office.Interop.Excel
Excel interop: _Worksheet or Worksheet?
(b) Interop Library Version
Check that the Office.Interop DLL you are using are relevant to the officeversion installed on the machine.
(c) Permissions and Protection issues
Check that the workbook is not ReadOnly or it is protected, you can refer to the following SO question:
Excel interop prevent showing password dialog
(d) Hidden Worksheets issue
Also make sure that the workbook does not contains hidden or temp worksheets, try to loop over all Worksheets in the Workbook and Debug the code to see what is going on.
(2) Add a new Worksheet
If you are looking to add a new worksheet to an existing workbook you can:
(a) Add it via Script-Task
You can use a similar code:
Excel._Worksheet newWorksheet;
newWorksheet = (Excel._Worksheet)ThisWorkbook.Worksheets.Add();
For more information, you can check the following links:
How to: Programmatically add new worksheets to workbooks
How to create a new worksheet in Excel file c#?
(b) Use Execute SQL Task
First you have to create an Excel Connection Manager, then add an Execute SQL Task, choose the Excel Connection and write a CREATE Statement, as example:
CREATE TABLE
`Excel Destination` (
`PromotionKey` INTEGER,
`PromotionAlternateKey` INTEGER,
`EnglishPromotionName` NVARCHAR(255),
`SpanishPromotionName` NVARCHAR(255),
`FrenchPromotionName` NVARCHAR(255),
`DiscountPct` DOUBLE PRECISION,
`EnglishPromotionType` NVARCHAR(50),
`SpanishPromotionType` NVARCHAR(50),
`FrenchPromotionType` NVARCHAR(50),
`EnglishPromotionCategory` NVARCHAR(50),
`SpanishPromotionCategory` NVARCHAR(50),
`FrenchPromotionCategory` NVARCHAR(50),
`StartDate` DATETIME,
`EndDate` DATETIME,
`MinQty` INTEGER,
`MaxQty` INTEGER
)
For more information, you can check the following links:
SSIS: Dynamically Generate Excel Table/Sheet

The Office Interop / Object Model API is based on running Office code in the context of your application. It expects to be running on the UI thread of an interactive (i.e. non-server) application.
See Considerations for server-side Automation of Office
If you ever do get this working, it will fail at just about the most inconvenient time.
If you need to manipulate Office documents on a server, use a server-side appropriate API like OpenXML

Related

Get current cell value from open Excel sheet using C#

I have an open instance of Excel which is already connected to via a COM process, which I have changed the value of one of the cells. In C# I can't get a connection to the sheet, but in python i can
Working Python code:
import xlwings as xw
wb = xw.Book('c:/users/me/Desktop/mysheet.xlsx')
sheet = wb.sheets['Sheet1']
print(sheet.range('B1').value) # returns the current value
Non-working C# code:
var xlApp = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
Workbook wb = xlApp.ActiveWorkbook; // returns null
Worksheet excelSheet = wb.ActiveSheet;
string test = excelSheet.Cells[1, 2].Value.ToString();
Is there a way to get C# to connect to this sheet, given it is already open via a COM automation from another software product?
Most of the online discussion around GetActiveObject is to talk to a specific instance of Excel if there are multiple instances running, I have the opposite problem, a single instance of Excel and multiple applications trying to connect to it.
Workbook wb = System.Runtime.InteropServices.Marshal.BindToMoniker(#"c:\users\me\Desktop\mysheet.xlsx") as Workbook;
should get the workbook even if it is already opened in Excel or not.
https://blogs.msdn.microsoft.com/eric_carter/2009/03/12/attaching-to-an-already-running-office-application-from-your-application-using-getactiveobject-or-bindtomoniker/

Excel Power Pivot export

I have a good skill in VBA and c# but a very low skill in Excel so I need help for my scenario.
I have an excel xlsx with some data inside.
Data comes from a Power Pivot table.
Assuming i'm using Excel 2018, i click on "Power Pivot" bar menu, then on "Manage".
I can see 4 tables.
I need a way "programatically" export the 4 tables to a csv.
With a simple c# app, I exported the sheet but data are incomplete because of filters and so on. And I cannot operate on the source excel because it come from a remote system.
Is there a way in VBA, or in .NET to iterate EVERY cell for every Power Pivot table in an Excel file?
I wrote something like:
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
xlApp = new Excel.Application();
var v = xlApp.Workbooks;
xlWorkBook = v.Open(bla bla...);
var s = xlWorkBook.Sheets[1];
var pt = s.PivotTables[1];
.. now I am stuck...
I had a try opening the xlsx file from another excel file, within a Module VBA, with no luck.
Please help me :-)
TY

Create Excel Sheet with LINEST via C#

I have a C# application which has to create an Excel file with formulas.
Simple formulas work fine.
But when I use LINEST(...) I get an exception.
Init objects:
using Microsoft.Office.Interop.Excel;
var Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
var currentWorksheet = xlWorkBook.Worksheets.get_Item(1);
string myLinestFormulaString ="LINEST(LN(C1:C10);$A1:$A10;TRUE;FALSE)";
The line below causes an exception HRESULT: 0x800A03EC
currentWorksheet.Cells[12, 3].Formula = myLinestFormulaString; // Write to C12
I know the HRESULT means that there is something wrong with the formula string.
Edit: Issue solved.
I use the German version of Excel. In C# I had to replace ';' with commas.
Excel's COM interface use the American list separators. That's why you need , instead of ; in your formular.
Try:
string myLinestFormulaString = "LINEST(LN(C1:C10),$A1:$A10,TRUE,FALSE)";

Open Excel workbook in background using interop

I'm wanting to import data from an Excel workbook without actually displaying the open workbook.
I could have sworn I had used the following code on a previous project and it had worked:
var excelApp = new Excel.Application { Visible = false };
var workbook = excelApp.Workbooks.Open(filePath);
Unfortunately when the workbook opens it is displayed to the user which is unnecessary for this application.
I'm using Microsoft Excel 15.0 Object Library on this project when previously I think it was version 12 or 13. Maybe this is the problem, or is my memory fading and the code is incorrect?
I know this is old but just in case anybody still needs this answer...
excelApp.Visible = false;
(excelApp being the name of the variable used for the excel application)

C# generating excel file and writing to cells

I am working on a project that runs MySQL queries on DB. I need to feed out the results to a excel sheet that I will be generating on the fly. I had started the code, using msdn tutorials as well as information I found on stackoverflow, however running the application leaves me with
"Object reference not set to an instance of an object."
At this point I just have the basic code started as I wanted to make this work before I started creating the entire spreadsheet in the code.
var excelApp = new Excel.Application();
excelApp.Visible = true;
Excel.Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
((Excel.Range)workSheet.Cells[1, 1]).Value = "Print Date:";
If I can provide any more info just ask. I greatly appreciate any information or insight you can provide me with!
I'd say that workSheet is being set to null as excelApp.ActiveSheet doesn't exist yet.
Here's some code that'll create a worksheet object you can use...
var application = new Application();
var workbooks = application.Workbooks;
var workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
var worksheets = (Sheets)workbook.Worksheets;
var worksheet = worksheets[1];
A few things to note when working with Excel:
Release every object with System.Runtime.InteropServices.Marshal.ReleaseComObject(object) when you're finished with it. If you don't, Excel won't exit when you're done.
Don't use double-dot references (i.e., object1.object2.value). If you do you can't release it properly as above.
Indexes always start from 1, not 0 (in my experience anyway).
The reason you get that error is, you have not created any worksheets in the Application.
Try doing this.
Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)excelApp.Worksheets.Add();

Categories

Resources