简体   繁体   中英

How to access data in sheet in my Visual Studio Office Excel workbook?

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

  1. load configuration data
  2. open a WinForm
  3. present configuration data on that form,

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?

EDIT

Please see project sample screencast here

I have a button on Sheet2, that should

  1. load some data from Sheet1
  2. initialize WinForm
  3. add it as a DataSource for a ComboBox on that WinForm

I can not find a way how to read data from that Sheet1...

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):

  1. the .NET type for Excel Cell is Excel.Range (at least I didn't find any other option)
  2. when reading cell that is empty in Excel file, it's value on .NET side is null, not ""
  3. values that seem to be strings on Excel side - can turn to be different types when loaded on c# side. I don't know if it's the best way, but I solved it like this:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM