简体   繁体   English

在C#中,如何使用Excel Interop加快写入多个单元格值的速度

[英]In C#, how do I use the Excel Interop to speed up writing several cell values

I have a piece of hardware for which I am getting 30 data points. 我有一个硬件,要获得30个数据点。 Each of these points is recorded in a spreadsheet at several different places before the sheet is made visible, then another program takes over the excel spreadsheet. 将这些点中的每一个点记录在电子表格中的几个不同位置之前,表格就变得可见,然后另一个程序接管excel电子表格。 It is required all these values are written to the spreadsheet before the other program takes over. 必须将所有这些值都写入另一个工作程序之前的电子表格。 If I write each cell individually, the writes are taking approximately 50ms, which takes about 1.25 seconds to complete the data acquisition. 如果我分别写入每个单元,则写入大约需要50毫秒,这大约需要1.25秒才能完成数据采集。

If I could write all the values to the spreadsheet at one time, I feel this will significantly speed up the writing of all these cells. 如果我可以一次将所有值写入电子表格,我认为这将大大加快所有这些单元格的写入速度。 The problem I see is that Ranges work very well for updating contiguous cells where as my data isn't contiguous. 我看到的问题是,由于我的数据不连续,因此Ranges非常适合更新连续的单元格。 Essentially, this would be an example of what I want to write: 本质上,这将是我要编写的示例:
A1 = 1 A1 = 1
B23 = a B23 = a
F8 = 2012/12/25 F8 = 2012/12/25
D53 = 4.1235 D53 = 4.1235
B2 = 5 B2 = 5

I have tried creating a range of "A1,B23,F8,D53,B2", then set the values using an array of values. 我尝试创建范围“ A1,B23,F8,D53,B2”,然后使用值数组设置值。 I tried 3 different arrays: object[5], object[1,5], and object[5,1]. 我尝试了3种不同的数组:object [5],object [1,5]和object [5,1]。 These all set the values of the specified cells in the range to the first index of the array I created in all cases. 这些都将范围内指定单元格的值设置为在所有情况下我创建的数组的第一个索引。

Is there a way to update these 30 cells data without iterating through the cells one at a time? 有没有一种方法可以更新这30个单元数据,而无需一次遍历一个单元?

Thanks, Tom 谢谢汤姆

如果您的体系结构允许,另一个想法是使用具有连续矩形范围的隐藏工作表,为其部分设置名称,并在所有其他工作表上使用这些名称。

I would define a rectangular range object that includes all the cells whose values you want to modify. 我将定义一个矩形范围对象,其中包含要修改其值的所有单元格。 Get a rectangular object[,] array from that range's value property. 从该范围的value属性获取一个矩形object[,]数组。 Write the new values to the array, and then set the range's value using the modified array. 将新值写入数组,然后使用修改后的数组设置范围的值。

You could write the values to contiguous cells that are somewhere out of the way, say in column X, and have formulae in the target cells that refer to these updated cells. 您可以将值写到不相干的连续单元格中,例如在X列中,并在目标单元格中​​具有引用这些更新单元格的公式。 So cell A1 would have the formula "=X1", cell B23 "=X2" and so on. 因此,单元格A1的公式为“ = X1”,单元格B23的公式为“ = X2”,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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