Domanda

Sto appena iniziando a giocherellare con Excel tramite C # per poter automatizzare la creazione e l'aggiunta a un file Excel.

Posso aprire il file e aggiornarne i dati e spostarmi tra i fogli di lavoro esistenti. Il mio problema è come posso aggiungere nuovi fogli?

Ho provato:

Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)excelApp.ThisWorkbook.Worksheets.Add(
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);

Ma vado sotto Eccezione COM e il mio googling non mi ha dato alcuna risposta.

  

Eccezione da HRESULT: 0x800A03EC La fonte è: " Interop.Excel "

Spero che qualcuno sia forse in grado di tirarmi fuori dalla mia miseria.

È stato utile?

Soluzione

Devi aggiungere un riferimento COM nel tuo progetto alla " Libreria di oggetti Microsoft Excel 11.0 " - o qualunque versione sia appropriata.

Questo codice funziona per me:

private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)
{
    Microsoft.Office.Interop.Excel.Application xlApp = null;
    Workbook xlWorkbook = null;
    Sheets xlSheets = null;
    Worksheet xlNewSheet = null;

    try {
        xlApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlApp == null)
            return;

        // Uncomment the line below if you want to see what's happening in Excel
        // xlApp.Visible = true;

        xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
                false, XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);

        xlSheets = xlWorkbook.Sheets as Sheets;

        // The first argument below inserts the new worksheet as the first one
        xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
        xlNewSheet.Name = worksheetName;

        xlWorkbook.Save();
        xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);
        xlApp.Quit();
    }
    finally {
        Marshal.ReleaseComObject(xlNewSheet);
        Marshal.ReleaseComObject(xlSheets);
        Marshal.ReleaseComObject(xlWorkbook);
        Marshal.ReleaseComObject(xlApp);
        xlApp = null;
    }
}
  

Nota che vuoi stare molto attento a pulire e rilasciare correttamente i riferimenti agli oggetti COM . In questa domanda StackOverflow è inclusa un'utile regola empirica: " Non usare mai 2 punti con oggetti COM " . Nel tuo codice; avrai davvero problemi con quello. Il mio codice demo sopra NON pulisce correttamente l'app Excel, ma è un inizio!

Alcuni altri collegamenti che ho trovato utili esaminando questa domanda:

Secondo MSDN

  

Per utilizzare l'interoperabilità COM, è necessario   amministratore o sicurezza di Power User   permessi.

Spero che sia d'aiuto.

Altri suggerimenti

Vorrei ringraziarti per alcune eccellenti risposte. @AR., Sei una stella e funziona perfettamente. Ieri sera avevo notato che il Excel.exe non si chiudeva; così ho fatto qualche ricerca e ho scoperto come rilasciare gli oggetti COM. Ecco il mio codice finale:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Excel;

namespace testExcelconsoleApp
{
    class Program
    {
        private String fileLoc = @"C:\temp\test.xls";

        static void Main(string[] args)
        {
            Program p = new Program();
            p.createExcel();
        }

        private void createExcel()
        {
            Excel.Application excelApp = null;
            Excel.Workbook workbook = null;
            Excel.Sheets sheets = null;
            Excel.Worksheet newSheet = null;

            try
            {
                FileInfo file = new FileInfo(fileLoc);
                if (file.Exists)
                {
                    excelApp = new Excel.Application();
                    workbook = excelApp.Workbooks.Open(fileLoc, 0, false, 5, "", "",
                                                        false, XlPlatform.xlWindows, "",
                                                        true, false, 0, true, false, false);

                    sheets = workbook.Sheets;

                    //check columns exist
                    foreach (Excel.Worksheet sheet in sheets)
                    {
                        Console.WriteLine(sheet.Name);
                        sheet.Select(Type.Missing);

                        System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                    }

                    newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing);
                    newSheet.Name = "My New Sheet";
                    newSheet.Cells[1, 1] = "BOO!";

                    workbook.Save();
                    workbook.Close(null, null, null);
                    excelApp.Quit();
                }
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(newSheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);

                newSheet = null;
                sheets = null;
                workbook = null;
                excelApp = null;

                GC.Collect();
            }
        }
    }
}

Grazie per tutto il tuo aiuto.

Un altro " alto tick " per AR ..., ma se non dovessi usare l'interop lo eviterei del tutto. Questo prodotto è in realtà abbastanza interessante: http://www.clearoffice.com/ e fornisce un'API molto intuitiva, completamente gestita, per la manipolazione eccellere file e sembra essere gratuito. (almeno per il momento) SpreadSheetGear è anche eccellente ma costoso.

i miei due centesimi.

  

Non dimenticare di includere Riferimento in Libreria oggetti Microsoft Excel 12.0 / 11.0

using Excel = Microsoft.Office.Interop.Excel;
// Include this Namespace

Microsoft.Office.Interop.Excel.Application xlApp = null;
Excel.Workbook xlWorkbook = null;
Excel.Sheets xlSheets = null;
Excel.Worksheet xlNewSheet = null;
string worksheetName ="Sheet_Name";
object readOnly1 = false;

object isVisible = true;

object missing = System.Reflection.Missing.Value;

try
{
    xlApp = new Microsoft.Office.Interop.Excel.Application();

    if (xlApp == null)
        return;

    // Uncomment the line below if you want to see what's happening in Excel
    // xlApp.Visible = true;

    xlWorkbook = xlApp.Workbooks.Open(@"C:\Book1.xls", missing, readOnly1, missing, missing, missing, missing, missing, missing, missing, missing, isVisible, missing, missing, missing);

    xlSheets = (Excel.Sheets)xlWorkbook.Sheets;

    // The first argument below inserts the new worksheet as the first one
    xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
    xlNewSheet.Name = worksheetName;

    xlWorkbook.Save();
    xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
    xlApp.Quit();
}
finally
{
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlNewSheet);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
    //xlApp = null;
}

Puoi usare OLEDB per creare e manipolare file Excel. Vedi questa domanda per link ed esempi.

Ecco un paio di cose che ho capito:

  1. Non puoi aprire più di un'istanza dello stesso oggetto contemporaneamente. Ad esempio, se installi un nuovo oggetto foglio Excel chiamato xlsheet1 devi rilasciarlo prima di creare un altro oggetto foglio Excel ex xlsheet2 . Sembra che COM perda traccia dell'oggetto e lascia un processo zombi sul server.

  2. L'uso del metodo open associato a excel.workbooks diventa anche difficile da chiudere se si hanno più utenti che accedono allo stesso file. Utilizzare invece il metodo Aggiungi, funziona altrettanto bene senza bloccare il file. per esempio. xlBook = xlBooks.Add (" C: \ location \ XlTemplate.xls ")

  3. Posiziona la tua garbage collection in un blocco o metodo separato dopo aver rilasciato gli oggetti COM.

COM non è sicuramente una buona strada da percorrere. Più specificamente, non c'è niente da fare se hai a che fare con l'ambiente web ...

Ho usato con successo i seguenti progetti open source:

  • ExcelPackage per formati OOXML (Office 2007)

  • NPOI per il formato .XLS (Office 2003)

Dai un'occhiata a questi post sul blog:

Creazione di fogli di calcolo Excel .XLS e .XLSX in C #

NPOI con tabella Excel e dinamica grafico

Questo è quello che ho usato per aggiungere un foglio di lavoro aggiuntivo

Workbook workbook = null;
Worksheet worksheet = null;

workbook = app.Workbooks.Add(1);
workbook.Sheets.Add();

Worksheet additionalWorksheet = workbook.ActiveSheet;

Ho avuto un problema simile a livello di componente aggiuntivo in VSTO, con l'eccezione HRESULT: 0x800A03EC durante l'aggiunta di un nuovo foglio.

  

Il codice di errore 0x800A03EC (o -2146827284) indica NAME_NOT_FOUND; nel   in altre parole, hai chiesto qualcosa e Excel non riesce a trovarlo.

Dominic Zukiewicz @ Errore Excel HRESULT: 0x800A03EC durante il tentativo di ottenere l'intervallo con il nome della cella

Quindi ho finalmente realizzato che questo libro di lavoro ha attivato l'eccezione. ActiveWorkbook è andato bene.

Excel.Worksheet newSheetException = Globals.ThisAddIn.Application.ThisWorkbook.Worksheets.Add(Type.Missing, sheet, Type.Missing, Type.Missing);
Excel.Worksheet newSheetNoException = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets.Add(Type.Missing, sheet, Type.Missing, Type.Missing);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top