【问题标题】:Interop - Speed of inserting into open excel instance互操作 - 插入打开的 excel 实例的速度
【发布时间】:2018-01-31 23:55:00
【问题描述】:

我正在寻找一个正在运行的 excel 实例并将数据插入其中一个工作表中。一切正常,但是插入数据非常慢。每个单元格约 0.25 秒。

有什么办法可以加快速度吗?

我一直在寻找一种不会逐个细胞进行的方法,但没有找到任何东西。

我的代码:

using System;
using System.Data;
using Microsoft.Office.Interop.Excel;
using Application = Microsoft.Office.Interop.Excel.Application;
using DataTable = System.Data.DataTable;


[STAThread]
static void Main()
{
    Application xlApp = null;

    try
    {
        xlApp = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    }
    catch (Exception)//Excel not open
    {
        return;
    }

    xlApp.Visible = true;

    var wb = xlApp.ActiveWorkbook;

    Worksheet ws = null;

    try
    {
        ws = (Worksheet)wb.Worksheets["SomeSheet"];
    }
    catch (Exception e)
    {
        return;
    }

    if (ws == null)
    {
        return;
    }

    var dt = new DataTable();

    dt = new DataTable();
    dt.Clear();
    dt.Columns.Add("Col1");
    dt.Columns.Add("Col2");
    for (int ii = 0; ii < 20; ii++)
    {
        DataRow row = dt.NewRow();
        row["Col1"] = "xxxx";
        row["Col2"] = "yyyy";
        dt.Rows.Add(row);
    }

    //Header
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        ws.Cells[1, i + 1] = dt.Columns[i].ColumnName;

    }

    //Data
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            ws.Cells[i + 2, j + 1] = dt.Rows[i][j];
        }
    }

}

【问题讨论】:

标签: c# excel office-interop


【解决方案1】:

您是否尝试过使用范围?将数组分配给范围以确保范围和数组的长度相同。

https://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.range.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

【讨论】:

  • 采纳您的建议,使用字符串 [,] 并分配给 Range.Value2 为我解决了性能问题。
猜你喜欢
  • 1970-01-01
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
相关资源
最近更新 更多