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)";
Related
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/
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
Following is my C# code,where i`m trying to unlock protected sheet by passing password,but it still not unlocking the sheet, I need to add some macro to the sheet .
Code:
const string excelFile = #"c:\temp\VBA\test.xlsm";
var excelApplication = new ExcelInterop.Application { Visible = true };
var targetExcelFile = excelApplication.Workbooks.Open(FileName:excelFile,Password:"12asQOl");
I can`t use "sendKeys" here,please help me on this.
Thanks
One piece of advice when working with VBA: start recording a macro of what you're trying to do then see the generated code.
Looks like you're trying to open a protected file, not unprotect a sheet.
I've found some old code of something like this (it's VB):
Dim WSheet As Worksheet
For Each WSheet In Worksheets
If WSheet.ProtectContents = True Then
WSheet.Unprotect Password:=MyPassword
Else
WSheet.Protect Password:=MyPassword
End If
Next WSheet
In your code you are passing the document password. You are not un-protecting the workbook.
Use the following code to un-protect the workbook:
targetExcelFile.Unprotect(password);
Let me know if you have any issues.
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();
Trying to make an excel file using this code:
app = new Excel.Application();
app.Visible = false;
object misValue = System.Reflection.Missing.Value;
workbook = app.Workbooks.Add(misValue);
worksheet = (Excel.Worksheet)workbook.Worksheets.get_Item(1);
and all get if I'm trying to do anything (worksheet.Cells[0,0] = "text")
results in {"Exception from HRESULT: 0x800A03EC"}
I've tried changing the locale:
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
and I've tried also setting "Trust access to the VBA project object model" to true.
Nothing helps.
any ideas ?
Does this happen when you write to any other cell?
This is based off 2003, but I don't think you can write into cell 0,0. The start of the cell is 1,1 which is (A,1)