0

我正在使用 ExcelDna 和 NetOffice 为 Excel 构建一个插件,并从各种来源获取数据并将其插入到工作表中。

我的问题是在工作表中插入数据真的很慢。

将一组值插入 Excel 的最有效方法是什么?

ResultCell[,] result = _currentView.GetResult(values, cursor);

int loopM = result.GetUpperBound(0);
int loopN = result.GetUpperBound(1);

for (int y = 0; y <= loopM; y++)
{
    for (int x = 0; x <= loopN; x++)
    {
        int a = xlCurrentCell.Row + row;
        int b = xlCurrentCell.Column + x;
        Excel.Range xlCell = (Excel.Range)xlActiveSheet.Cells[a, b];
        _SetValue(xlCell, result[y, x]);
    }
    row++;
}

...

private void _SetValue(Excel.Range xlCell, ResultCell cell)
{
    xlCell.ClearFormats();
    object value = cell.Value;

    if (value is ExcelError)
    {
        value = ExcelUtils.ToComError((ExcelError) value);
    }
    else if (ExcelUtils.IsNullOrEmpty(value))
    {
        value = "";
    }

    xlCell.Value = value;
    if (!string.IsNullOrEmpty(cell.NumberFormat))
    {
        xlCell.NumberFormat = cell.NumberFormat;
    }
}

问题是每次插入都会变成屏幕更新吗?我试过:

Excel.Application xlApp = new Excel.Application(null, ExcelDna.Integration.ExcelDnaUtil.Application);

xlApp.ScreenUpdating = false;

但这没有任何效果。

4

1 回答 1

1

每个单元格设置数据很慢。您可以将大范围的值设置为一组值,这将大大加快。

暂时关闭屏幕更新和重新计算也会有所帮助。

有关冗长而详细的讨论,包括使用 Excel-DNA 加载项中的 C API 的代码,请参阅在实时(未保存)Excel 数据和 C# 对象之间进行接口的最快方式

于 2015-02-01T13:57:29.633 回答