C# 如何使用 foreach 方法循环 Excel 命名范围

问题描述 投票:0回答:1

我需要循环一些Excel数据,但每个文件中有100万条数据。

我尝试使用“for”和“Parallel.For”进行循环,但速度太慢,因此我想尝试使用foreach,但我不知道如何制作。 Parallel.For 代码如下:

Parallel.For(2, lastUsedRow, i =>
       {
           int AddValue = DValue + 1;
           DValue = AddValue;
           currentsheet.Cells[1, 1].Value = AddValue + "/" + lastUsedRow;
           if (currentsheet.Cells[i, 3].Value != "")
           {
               currentsheet.Cells[i, 3].Value = Regex.Replace(currentsheet.Cells[i, 3].Text, "[ \\[ \\] \\^ \\-_*×――(^)(^)$%~!@#$…&%¥—+=<>《》!!???::•`·、。,;,.;\"‘’“”-]", "");
               currentsheet.Cells[i, 3].Value = currentsheet.Cells[i, 3].Text.ToUpper();
               currentsheet.Cells[i, 3].Value = currentsheet.Cells[i, 3].Text.Replace(" ", "");
           }
           else
           {
               currentsheet.Cells[i, 3].Value = "";
           }
           string COLVALUE = currentsheet.Cells[i, 3].Text;
           if (Regex.Matches(COLVALUE, "[a-zA-Z]").Count != 0 & COLVALUE.Length != 12)
           {
               currentsheet.Cells[i, 3].Value = "";
               currentsheet.Cells[i, 4].Value = COLVALUE;
           }
       });

这里的每个朋友都知道如何在行范围或命名范围中进行 foreach 循环吗?非常感谢。

c# excel vsto
1个回答
0
投票

只是建议在这里尝试一下。您可以将列表分解为子范围,例如每个 10k,然后将这些范围读入 C# 内存数组,并直接在 C# 中(而不是单独的行)对数组执行更新。然后将整个数组作为单个范围粘贴回 Excel 中。粘贴整个范围是一个单一操作,比一次迭代第 1 行要快得多。

您可以尝试一次执行一个范围,或者并行并尝试不同的尺寸范围。

我知道在 VBA 中使用内存数组比访问工作表/行要快得多。我认为这与 C# 相同,并且推测性能增益会更大,因为 C# 是互操作的,而 VBA 不是。

© www.soinside.com 2019 - 2024. All rights reserved.