C# Excel Interop Slow when looping through cells

后端 未结 4 836
星月不相逢
星月不相逢 2021-02-06 05:38

I am trying to extract all text data from an Excel document in C# and am having performance issues. In the following code I open the Workbook, loop over all worksheets, and loop

4条回答
  •  無奈伤痛
    2021-02-06 06:01

    Excel and C# run in different environments completely. C# runs in the .NET framework using managed memory while Excel is a native C++ application and runs in unmanaged memory. Translating data between these two (a process called "marshaling") is extremely expensive in terms of performance.

    Tweaking your code isn't going to help. For loops, string construction, etc. are all blazingly fast compared to the marshaling process. The only way you are going to get significantly better performance is to reduce the number of trips that have to cross the interprocess boundary. Extracting data cell by cell is never going to get you the performance you want.

    Here are a couple options:

    1. Write a sub or function in VBA that does everything you want, then call that sub or function via interop. Walkthrough.

    2. Use interop to save the worksheet to a temporary file in CSV format, then open the file using C#. You will need to loop through and parse the file to get it into a useful data structure, but this loop will go much faster.

    3. Use interop to save a range of cells to the clipboard, then use C# to read the clipboard directly.

提交回复
热议问题