Reputation: 2548
I need to create a "Document level customization" with C# code (not and Excel Add-in!)
I created a Visual Studio Office Excel 2010 Workbook project type. This creates a workbook with 3 sheets in my project. I added some "configuration" information to one of those sheets.
I need to access this configuration information programmatically (Sheet1
contains a button
- pressing on that button should
but somehow I can't find how to do that...
If I try to initialize Sheet1
class, compiler expects two parameters - Microsoft.Office.Tools.Excel.Factory
and IServiceProvider
, but I am calling this from a button that is placed on Sheet2 - so it's after Excel Workbook is already opened... shouldn't Sheet1 be initialized automatically?
So, how can I access Sheet1
from my VSTO project's c# code?
Please see project sample screencast here
I have a button on Sheet2, that should
I can not find a way how to read data from that Sheet1...
Upvotes: 0
Views: 2806
Reputation: 2548
It seems, that there are not a lot developers (at least at stackoverflow) that work with Excel workbooks in Visual Studio / VSTO), but still this is is how I got this basic stuff working - in case if this is helpful to someone else
Since my code was in the Worksheet's *.cs file it turned out I can access project's xlsx file this way:
var excel = (Excel.Application)this.Application;
var xlbook = (Excel.Workbook)excel.ActiveWorkbook;
var worksheets = xlbook.Worksheets;
var sheet = (Excel.Worksheet)worksheets["Sheet3"];
int row = 2;//1st row for column titles
while (!string.IsNullOrEmpty(((Excel.Range)sheet.Cells[row, 2]).Value))
{
var weight = ((Excel.Range)sheet.Cells[row, 3]).Value;
row++;
}
Some additional things about processing data from Excel sheet in c# code, I found out (maybe that's helpful for someone):
var weight = (((Excel.Range)sheet.Cells[row, 3]).Value);
if (weight is double)
{
product.Weight = ((double)((Excel.Range)sheet.Cells[row, 3]).Value).ToString();
}
else if (weight is string)
{
product.Weight = ((Excel.Range)sheet.Cells[row, 3]).Value;
}
Upvotes: 3