[英]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!) 我需要使用C#代码创建一个“文档级自定义”(不是Excel加载项!)
I created a Visual Studio Office Excel 2010 Workbook project type. 我创建了Visual Studio Office Excel 2010工作簿项目类型。 This creates a workbook with 3 sheets in my project. 这将在我的项目中创建一个包含3张纸的工作簿。 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 我需要以编程方式访问此配置信息( Sheet1
包含一个button
-按下该按钮应
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? 如果我尝试初始化Sheet1
类,则编译器需要两个参数Microsoft.Office.Tools.Excel.Factory
和IServiceProvider
,但是我是通过Sheet2上的按钮调用此参数的-因此它是在 Excel Workbook已打开之后... Sheet1是否不应该自动初始化?
So, how can I access Sheet1
from my VSTO project's c# code? 那么,如何从VSTO项目的c#代码访问Sheet1
?
Please see project sample screencast here 请在此处查看项目样本截屏
I have a button on Sheet2, that should 我在Sheet2上有一个按钮,应该
I can not find a way how to read data from that Sheet1... 我找不到一种方法来从该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 似乎没有很多开发人员(至少在stackoverflow上)可以在Visual Studio / VSTO中使用Excel工作簿),但这仍然是我使这些基本知识起作用的方式-以防万一这对其他人有帮助
Since my code was in the Worksheet's *.cs file it turned out I can access project's xlsx file this way: 由于我的代码在工作表的* .cs文件中,因此我可以通过以下方式访问项目的xlsx文件:
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): 我发现了一些有关使用C#代码处理Excel工作表中的数据的其他事项(可能对某人有用):
var weight = (((Excel.Range)sheet.Cells[row, 3]).Value); 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.