从 VSTO 项目中的 Excel 工作簿读取五十万条记录
本文关键字:读取 五十万 记录 工作簿 Excel VSTO 项目 | 更新日期: 2023-09-27 18:32:39
我正在尝试使用VSTO和创建Visual Studio 2010 Office工作簿项目在Excel中构建模拟工具。此工作簿中的一个工作表将包含大约五十万条记录。理想情况下,我想读取在模拟中使用它们的所有记录,然后输出一些统计信息。到目前为止,当我试图一次性获取整个范围然后单元格时,我遇到了OutOfMemory例外。有没有人对我如何阅读所有数据或建议有其他想法?
这是我的代码:
Excel.Range range = Globals.shData.Range["A2:AX500000"];
Array values = (Array)range.Cells.Value;

批量获取,并在内存中组装一个内存量稍低的模型怎么样?
var firstRow = 2;
var lastRow = 500000;
var batchSize = 5000;
var batches = Enumerable
.Range(0, (int)Math.Ceiling( (lastRow-firstRow) / (double)batchSize ))
.Select(x =>
string.Format(
"A{0}:AX{1}",
x * batchSize + firstRow,
Math.Min((x+1) * batchSize + firstRow - 1, lastRow)))
.Select(range => ((Array)Globals.shData.Range[range]).Cells.Value);
foreach(var batch in batches)
{
foreach(var item in batch)
{
//reencode item into your own object collection.
}
}
这不是 Excel 问题,而是一般的 C# 问题。 与其收集内存中的所有行,不如生成行并迭代计算统计信息。
例如
class Program
{
static void Main(string[] args)
{
var totalOfAllAges = 0D;
var rows = new ExcelRows();
//calculate various statistics
foreach (var item in rows.GetRow())
{
totalOfAllAges += item.Age;
}
Console.WriteLine("The total of all ages is {0}", totalOfAllAges);
}
}
internal class ExcelRows
{
private double rowCount = 1500000D;
private double rowIndex = 0D;
public IEnumerable<ExcelRow> GetRow()
{
while (rowIndex < rowCount)
{
rowIndex++;
yield return new ExcelRow() { Age = rowIndex };
}
}
}
/// <summary>
/// represents the next read gathered by VSTO
/// </summary>
internal class ExcelRow
{
public double Age { get; set; }
}