2017-08-23 1 views
0

Je trouve une instance en cours d'exécution d'Excel et j'insère des données dans l'une des feuilles de calcul. Tout fonctionne, mais l'insertion de données est très lente. ~ 0,25 secondes pour chaque cellule.Interop - Vitesse d'insertion dans l'instance Excel ouverte

Y a-t-il un moyen de rendre cela plus rapide?

Je cherchais une approche qui ne va pas cellule par cellule, mais qui n'a rien trouvé.

Mon code:

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]; 
     } 
    } 

} 
+0

Il y a longtemps que je l'ai fait tout Excel/Interop but..you besoin de regarder l'objet Range et sa propriété Value. https://msdn.microsoft.com/EN-US/library/microsoft.office.interop.excel.range.value.aspx Il y a beaucoup d'exemples – Adrian

+0

Duplication possible de [Un moyen plus efficace d'écrire une table de données pour exceller?] (https://stackoverflow.com/questions/27504142/more-efficient-way-to-write-data-table-to-excel) – Slai

Répondre