C#-Projekt: Zugriff auf Excel-Dateien

URL dieses Beitrags: http://blog.stefan-macke.com/2006/06/28/c-projekt-zugriff-auf-excel-dateien/

Der Zugriff auf Excel-Dateien und -Funktionen mit C# ist eigentlich recht einfach. Zunächst muss ein Verweis auf die COM-Bibliothek Microsoft Excel 11.0 Object Library hinzugefügt und dann noch der entsprechende Namespace inkludiert werden mittels:

  1. using Microsoft.Office.Interop.Excel;

Änderungen bei Excel 2007: Es muss die COM-Bibliothek Microsoft Excel 12.0 Object Library verwendet werden.

Dann kann man munter drauflos programmieren, vielleicht wie folgt:

  1. // benötigte Objekte vorbereiten
  2. Microsoft.Office.Interop.Excel.Application excel = null;
  3. Workbook wb = null;
  4. try
  5. {
  6.     // Excel starten
  7.     excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
  8.     excel.Visible = false;
  9.  
  10.     // Datei öffnen
  11.     wb = excel.Workbooks.Open(
  12.         this.dateiname,
  13.         ExcelKonstanten.UpdateLinks.DontUpdate,
  14.         ExcelKonstanten.ReadOnly,
  15.         ExcelKonstanten.Format.Nothing,
  16.         "", // Passwort
  17.         "", // WriteResPasswort
  18.         ExcelKonstanten.IgnoreReadOnlyRecommended,
  19.         XlPlatform.xlWindows,
  20.         "", // Trennzeichen
  21.         ExcelKonstanten.Editable,
  22.         ExcelKonstanten.DontNotifiy,
  23.         ExcelKonstanten.Converter.Default,
  24.         ExcelKonstanten.DontAddToMru,
  25.         ExcelKonstanten.Local,
  26.         ExcelKonstanten.CorruptLoad.NormalLoad);
  27.  
  28.     // Arbeitsblätter lesen
  29.     Sheets sheets = wb.Worksheets;
  30.  
  31.     // ein Arbeitsblatt auswählen...
  32.     Worksheet ws = (Worksheet)sheets.get_Item("Blatt 1");
  33.     // ...oder eine Zelle
  34.     Range range = (Range)ws.get_Range("A1", "A1");
  35.     // deren Wert auslesen
  36.     string zellwert = range.Value2.ToString();
  37. }
  38. finally
  39. {
  40.     wb.Close(false, null, null);
  41.     excel.Quit();
  42. }

Ich habe mir der Einfachheit halber die Werte, die als Parameter für die Methode Worbook.Workbooks.Open benötigt werden, in eine kleine Hilfsklasse geschrieben. Die Werte habe ich von der Microsoft-Seite.

  1. /// <summary>
  2. /// Diese Klasse enthält alle Konstanten, die beim Zugriff auf Excel
  3. /// benötigt werden. Die Beschreibungen sind von Microsoft übernommen
  4. /// und daher noch auf Englisch.
  5. /// </summary>
  6. private static class ExcelKonstanten
  7. {
  8.     /// <summary>
  9.     /// Specifies the way links in the file are updated. If this
  10.     /// argument is omitted, the user is prompted to specify how
  11.     /// links will be updated. Otherwise, this argument is one of
  12.     /// the values listed in the following table.
  13.     /// </summary>
  14.     public enum UpdateLinks
  15.     {
  16.         DontUpdate = 0,
  17.         ExternalOnly = 1,
  18.         RemoteOnly = 2,
  19.         ExternalAndRemote = 3
  20.     };
  21.  
  22.     /// <summary>
  23.     /// True to open the workbook in read-only mode.
  24.     /// </summary>
  25.     public const bool ReadOnly = true;
  26.     public const bool ReadWrite = false;
  27.  
  28.     /// <summary>
  29.     /// If Microsoft Excel is opening a text file, this argument
  30.     /// specifies the delimiter character, as shown in the following
  31.     /// table. If this argument is omitted, the current delimiter
  32.     /// is used.
  33.     /// </summary>
  34.     public enum Format
  35.     {
  36.         Tabs = 1,
  37.         Commas = 2,
  38.         Spaces = 3,
  39.         Semicolons = 4,
  40.         Nothing = 5,
  41.         CustomCharacter = 6
  42.     };
  43.  
  44.     /// <summary>
  45.     /// True to have Microsoft Excel not display the read-only
  46.     /// recommended message (if the workbook was saved with the
  47.     /// Read-Only Recommended option).
  48.     /// </summary>
  49.     public const bool IgnoreReadOnlyRecommended = true;
  50.     public const bool DontIgnoreReadOnlyRecommended = false;
  51.  
  52.     /// <summary>
  53.     /// If the file is a Microsoft Excel 4.0 add-in, this argument
  54.     /// is True to open the add-in so that its a visible window.
  55.     /// If this argument is False or omitted, the add-in is opened
  56.     /// as hidden, and it cannot be unhidden. This option doesn't
  57.     /// apply to add-ins created in Microsoft Excel 5.0 or later.
  58.     /// If the file is an Excel template, True to open the specified
  59.     /// template for editing. False to open a new workbook based on
  60.     /// the specified template. The default value is False.
  61.     /// </summary>
  62.     public const bool Editable = true;
  63.     public const bool NotEditable = false;
  64.  
  65.     /// <summary>
  66.     /// If the file cannot be opened in read/write mode, this
  67.     /// argument is True to add the file to the file notification
  68.     /// list. Microsoft Excel will open the file as read-only, poll
  69.     /// the file notification list, and then notify the user when
  70.     /// the file becomes available. If this argument is False or
  71.     /// omitted, no notification is requested, and any attempts to
  72.     /// open an unavailable file will fail.
  73.     /// </summary>
  74.     public const bool Notify = true;
  75.     public const bool DontNotifiy = false;
  76.  
  77.     /// <summary>
  78.     /// The index of the first file converter to try when opening
  79.     /// the file. The specified file converter is tried first; if
  80.     /// this converter doesnt recognize the file, all other converters
  81.     /// are tried. The converter index consists of the row numbers
  82.     /// of the converters returned by the FileConverters property.
  83.     /// </summary>
  84.     public enum Converter
  85.     {
  86.         Default = 0
  87.     };
  88.  
  89.     /// <summary>
  90.     /// True to add this workbook to the list of recently used files.
  91.     /// The default value is False.
  92.     /// </summary>
  93.     public const bool AddToMru = true;
  94.     public const bool DontAddToMru = false;
  95.  
  96.     /// <summary>
  97.     /// True saves files against the language of Microsoft Excel
  98.     /// (including control panel settings). False (default) saves
  99.     /// files against the language of Visual Basic for Applications
  100.     /// (VBA) (which is typically US English unless the VBA project
  101.     /// where Workbooks.Open is run from is an old internationalized
  102.     /// XL5/95 VBA project).
  103.     /// </summary>
  104.     public const bool Local = true;
  105.     public const bool NotLocal = false;
  106.  
  107.     public enum CorruptLoad
  108.     {
  109.         NormalLoad = 0,
  110.         RepairFile = 1,
  111.         ExtractData = 2
  112.     };
  113. }
Füge diesen Artikel zu deinen Bookmarks hinzu Diese Icons verzweigen auf soziale Netzwerke bei denen Nutzer neue Inhalte finden und mit anderen teilen können.
  • del.icio.us
  • bodytext
  • MisterWong
  • Reddit
  • Technorati
  • Spurl
  • description

Kommentare zu diesem Beitrag

  1. Gravatar Suter
    Am 30. October 2007 um 09:30 Uhr

    Wiso kann man das den zweiten Codeteil nicht kopieren??
    Ansonsten gut:)
    Grüsse

  2. Gravatar Stefan
    Am 30. October 2007 um 11:26 Uhr

    Also ich kann alles kopieren!?

  3. Gravatar Suter
    Am 30. October 2007 um 12:15 Uhr

    Ich kann den zweiten Teil mit der Maus nicht mal markieren...Benutze IE 6.0

  4. Gravatar Nico
    Am 15. November 2007 um 15:07 Uhr

    Super! funktioniert alles...
    bis, dass beim Aufruf nicht das gewünschte Blatt aufgerufen wird.
    ist doch in dieser funktion: //Ein Arbeitsblatt auswählen
    habe es bei mir aber richtig angepasst!
    Funkrioniert dieser version??:S

  5. Gravatar Stefan
    Am 17. November 2007 um 18:33 Uhr

    Die Funktion nutze ich seit längerer Zeit wie oben abgebildet. Bau doch mal ein try-catch drum und schau, was das genaue Problem ist...

  6. Gravatar Mathias
    Am 29. May 2008 um 12:41 Uhr

    Da ich mitbekommen habe, dass hier jemand Ahnung hatte, hoffe ich das du noch diesen Beitrag liest obwohl der Thread schon alt ist ... aber was mache ich falsch wenn ich diese Fehlermeldung bekomme.

    Error: Das COM-Objekt des Typs "Microsoft.Office.Interop.Excel.WorkbookClass" kann nicht in den Schnittstellentyp "Microsoft.Office.Interop.Excel.Workbooks" umgewandelt werden. Dieser Vorgang konnte nicht durchgeführt werden, da der QueryInterface-Aufruf an die COM-Komponente für die Schnittstelle mit der IID "{000208DB-0000-0000-C000-000000000046}" aufgrund des folgenden Fehlers nicht durchgeführt werden konnte: Schnittstelle nicht unterstützt (Ausnahme von HRESULT: 0x80004002 (E_NOINTERFACE)). Line: WindowsFormsApplication2

    Danke für die Hilfe

  7. Gravatar Robsen
    Am 24. July 2008 um 00:30 Uhr

    selber Fehler wie Matthias... auch mit der msdn-website-anleitung...

  8. Gravatar Hannes
    Am 16. September 2008 um 08:19 Uhr

    Hast du den oben angegebenen Quellcode wirklich 1:1 verwendet?

  9. Gravatar Stefan
    Am 16. September 2008 um 13:24 Uhr

    Hallo Hannes.
    Ich habe den Code aus meinem lauffähigen Programm kopiert. Hast du alle Verweise eingefügt? Bei mir läuft's mit Excel 2003...

  10. Gravatar Andy
    Am 24. November 2008 um 12:19 Uhr

    Hallo,

    in welcher Form muss ich denn den Pfad und den Dateinamen eingeben?

    Z.B. wenn ich das C#-Projekt unter
    c:\csharp\projekt1
    gespeichert habe und meine Datei liegt auf
    c:\eigenedateien\mappe1.xls

    Wenn ich an Stelle von
    this.dateiname
    folgendes eingebe:
    c:\eigenedateien\mappe1.xls
    dann funktioniert das nicht.

    Fehlermeldung: Unerwartetes Zeichen "\".

    Auch mit Anführungsstrichen (" bzw. ') funktioniert das nicht.
    Fehlermeldung: Nicht erkannte Escapesequenz

  11. Gravatar Stefan
    Am 24. November 2008 um 13:20 Uhr

    @Andy: Du musst natürlich die Backslashes escapen. Entweder separat oder gleich ein "@" vor den String: "c:\\eigenedateien\\mappe1.xls" oder @"c:\eigenedateien\mappe1.xls".

  12. Gravatar Andreas
    Am 17. December 2008 um 20:34 Uhr

    Hallo,

    ich bekomme beim Aufruf von

    Sheets sheets = wb.Worksheets;

    stets den Fehler

    Eine Ausnahme (erste Chance) bei 0x7c812aeb in KppSAPServer.exe: 0x80010108: Das aufgerufene Objekt wurde von den Clients getrennt.

  13. Gravatar Stefan
    Am 18. December 2008 um 00:15 Uhr

    @Andreas: Dazu kann ich dir leider nichts sagen. Du wirst wohl mal den Debugger anschmeißen müssen :-(

  14. Gravatar Andreas
    Am 18. December 2008 um 15:28 Uhr

    @stefan: Gut, dass ich ab übermorgen Urlaub hab. Ich habe den Code in eine Methode ausgelagert und übersehen, dass das Excel im finally block geschlossen wird ;-(. Dein Code funktioniert problemlos.

Einen Kommentar schreiben

XHTML: Diese Tags sind erlaubt: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>