我的任务是为 Excel 2007 创建一个从自定义数据源读取数据的插件。我已经有了读取数据的代码。它是用 C# 编写的并返回对象。这是针对银行系统的,我无法直接访问数据。必须向 C# DLL 提供用户 ID、密码和硬件生成的 key 以获取最新数据。
我的老板希望数据每分钟自动更新一次,或者使用 Excel 提供的刷新功能手动更新。所以我需要让数据在 Excel 中显示,就好像它来自标准数据库连接一样。
我四处寻找起点,但我正在努力寻找一些有助于满足这一非常具体要求的信息。谁能帮忙?
最佳答案
开始下载 VSTO (Visual Studio Tools for Office)这将允许您创建 C# Excel 加载项。
在 Visual Studio 中创建新项目时,您将看到 Office,并且可以从中选择 Excel。
从那里开始,完成后您可以回来提出更具体的问题。
使用 Excel 的一些有用技巧。
选择事件工作表:
Excel.Worksheet sheet = this.Application.ActiveSheet as Excel.Worksheet;
选择特定范围(在本例中为 A1 - B5):
Excel.Range range = sheet.get_Range("A1", "B5") as Excel.Range;
将值设置为整个范围:
range.Value2 = 2; //will set every cell in A1 through B5 to 2
您可以从二维数组的范围中获取值,例如:
object[,] values = range.Value2 as object[,];
//this will return an multidimensional array representing rows and cols
//as you see in the range. in this case the array is filed with "2"
然后您可以更改整个数组中的值并应用回范围:
values[2, 2] = 4; //will change the value to 4 in row 2, col 2 of the *range*
range.Value2 = values; //set back the whole range to the array
您可以使用此技术一次更新整个范围,方法是先准备一个数组,然后将其设置为范围值。
从范围内的特定单元格获取值(设置值的方法相同,但相反)。
Excel.Range cell = range.Cells[1,1] as Excel.Range; //this will take the cell from row 1, cell 1. if you used array this would be values[1,1]
string value = (cell.Value2 ?? "").ToString();
这应该允许您在 Excel 中执行基本任务,您可以设置值、获取值和选择范围。如果您有更具体的问题,请回来。
别忘了,来自 Excel 的数组是从 1 开始的,而不是从零开始的!!!
关于c# - 如何创建读取自定义数据的 Excel 加载项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2312037/