使用 Excel 互操作设置单元格值
好的,所以我尝试使用 Excel 互操作库设置单元格的值。我可以通过以下方式做到这一点:
sheet.Cells[row, col] = value;
但是对于我设置的数量来说,速度非常慢。所以我试图走这条路:
Range excelRange = sheet.UsedRange;
excelRange.Cells.set_Item(row, col, value);
代码执行,但没有数据放入单元格中。对我所缺少的有什么建议吗?谢谢!
Ok, so I'm trying to set the value of a cell with the excel interop library. I am able to do it with the following:
sheet.Cells[row, col] = value;
but it's terribly slow for how many I'm setting. So I'm trying to go this route:
Range excelRange = sheet.UsedRange;
excelRange.Cells.set_Item(row, col, value);
The code executes, but no data is put in the cell. Any suggestions on what I'm missing? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您禁用了屏幕更新 (
Application.ScreenUpdating = false
),您的第一种方法应该适用于任何合理(以及大量不合理)数量的单元格。 知识库文章描述了如何使用 C# 按行和列访问设置单元格。Your first method should work fine for any reasonable (and a lot of unreasonable) amounts of cells, provided you have disabled screen updating (
Application.ScreenUpdating = false
). The Knowledgebase Article describing how to set cells using C# accesses by row and column as well.您是否尝试过一次设置所有值,而不是迭代数组并一次设置一个单元格?这样,您只需通过 COM 边界传递数据一次,而不是每个单元传递一次。
Excel 在这方面非常灵活。尝试以下操作:
您应该比迭代要设置的每个单元格更快。
除此之外,按照安迪的建议关闭 ScreenUpdated,并考虑将计算设置为手动,直到完成复制过程。
Have you tried setting all of the values at once, rather than iterating through your array and setting one cell at a time? That way you only have to pass data over the COM boundary once, rather than once per cell.
Excel is very flexible in this regard. Try the following:
You should this faster than iterating over each of the cells you're wanting to set.
Other than that, turn off ScreenUpdated as Andy suggests and also consider setting calculation to manual until you've finished your copy process.
简单的解决方案,但在这里您需要通过在 nuget console
Install-Package Microsoft.Office.Interop.Excel 中写入来安装 Package Microsoft.Office.Interop.Excel
Simple solution but here you will need to install Package Microsoft.Office.Interop.Excel by writting in nuget console
Install-Package Microsoft.Office.Interop.Excel
请尝试
Please try