Excel mit C# lesen

In einem Ferialpraktikum hatte ich einmal das Problem, dass ich eine Exceldatei aus einer C# Anwendung lesen musste. Dazu habe ich mir 2 Klassen geschrieben. myExcelApplication, welches mir eine Instanz von Microsoft Excel öffnet und nach Beendigung wieder schließt. Und myWorkbook, welche mir den Zugriff auf ein Workbook ermöglicht.

Wichtig sind vor allem die Referenzen. Man muss Microsoft.Office.Core sowie Microsoft.Office.Interop.Excel einbinden, damit es sicher funktioniert :)

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices; //Für DllImport!
using System.Diagnostics; //Für Process

myExcelApplication:

public class myExcelApplication : IDisposable
{
	#region user32 Funktionen
	// Windows OS Funktionen deklarieren
	[DllImport("user32")]
	private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

	[DllImport("user32.dll", SetLastError = true)]
	static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

	// Ende Os Funktionen
	#endregion

	public Excel.ApplicationClass ExApp; //Besitzt alle Excelfunktionen
	private string ApplicationID; //Ist meine Programmid
	private IntPtr hWnd; // Window Handle
	private int iProcID; // Prozess ID des markierten EXCELs
	private Process p = null; // entsprechendes Process object
	public myExcelApplication()
	{
		//defaulteinstellungen
		System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
		this.ApplicationID = "Excel_" + System.Guid.NewGuid().ToString().ToUpper(); //ID erzeugen
		this.ExApp = new Excel.ApplicationClass(); //Excelklasse zuweisen
		this.ExApp.DisplayAlerts = false; //keine Warnmeldungen Anzeigen
		this.ExApp.AskToUpdateLinks = false; //Updateabfrage deaktivieren
		this.ExApp.Visible = false; //unsichtbar
		this.ExApp.Caption = this.ApplicationID; //Id zuweisen

	}
	~myExcelApplication()
	{
		this.Dispose();
	}

	#region IDisposable Members

	public void Dispose()
	{
		/*
		 * Folgendes funktioniert nicht:
		 * ExApp.Application.Quit(); oder this.ExApp.Quit();
		 * Leider weiß ich nicht mehr woher ich das habe.
		 * Aber deswegen haben wir die EXCEL Applikation markiert
		 */
		hWnd = FindWindow(null, ApplicationID);
		if (hWnd == IntPtr.Zero) return;
		// zu dem Fenster holen wir uns die Prozess-ID ...
		GetWindowThreadProcessId(hWnd, out iProcID);
		if (iProcID == 0) return;
		// erzeugen ein entsprechendes .NET Prozess Objekt ..
		p = Process.GetProcessById((int)iProcID);
		if (p == null) return;
		// jetzt ist Feierabend ...
		p.CloseMainWindow();    // schliesse Fenster
		p.Refresh();            // gebe alle Prozess-Informationen frei
		if (p != null)
		{
			p.Kill();               // und tschuess ...
		}
	}

	#endregion
}

myWorkbook:

public class myWorkbook
{
	public Excel.Workbook myWb;
	public string Datei;
	public myExcelApplication ExApp;
	public bool schreibschutz = false;
	private bool _calculation;
	public bool calculation
	{
		get { return this._calculation; }
		set
		{
			this._calculation = value;
			this.calculate();
		}
	}
	public string aktivsheet;

	public myWorkbook(string datei, myExcelApplication EApp)
	{
		this.Datei = datei;
		this.ExApp = EApp;
	}
	public myWorkbook()
	{
		//leerer konstruktor
	}
	public void open()
	{
		try
		{
			this.myWb = ExApp.ExApp.Workbooks.Open(this.Datei, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
		}
		catch (Exception e)
		{
			//
		}
		//this.myWb = ExApp.ExApp.Workbooks.Open(this.Datei, 0, true, 5, "", "", true,Excel.XlPlatform.xlWindows, "t", false, false, 0, true, false, false);

		if (this.myWb.ReadOnly) { this.schreibschutz = true; }
		this.calculation = false; //Abschalten der automatischen Berechnung
	}
	public void close()
	{
		object Save = Excel.XlSaveAction.xlSaveChanges; //Speichern oder nicht speichern Variable hier setzen
		this.calculation = true; //Noch einmal schnell rechnen lassen vorm schließen
		this.myWb.Close(Save, Type.Missing, Type.Missing); //schließen
	}
	private void calculate()
	{
		//Schaltet automatische Berechnung ab bzw. aktiviert sie wieder
		if (!this.calculation)
		{
			this.ExApp.ExApp.Calculation = Excel.XlCalculation.xlCalculationManual;
		}
		else
		{
			this.ExApp.ExApp.Calculation = Excel.XlCalculation.xlCalculationAutomatic;
			this.ExApp.ExApp.Calculate();
		}
	}
	public Excel.Range Zelle(int Zeile, int Spalte)
	{
		return (Excel.Range)((Excel.Worksheet)this.myWb.Worksheets[this.aktivsheet]).Cells[Zeile, Spalte];
	}
	public Excel.Range Zelle(int Zeile, int Spalte, string Worksheet)
	{
		return (Excel.Range)((Excel.Worksheet)this.myWb.Worksheets[Worksheet]).Cells[Zeile, Spalte];
	}
}

Hier ein Beispiel, wie man mit diesen Klassen, die Erste Zelle des Blattes “Tabelle1″ auslesen kann:

//Applikation starten
myExcelApplication EApp = new myExcelApplication();
//Workbook erzeugen
myWorkbook ExcelFile = new myWorkbook("c:\test.xls", EApp);
//Excelfile öffnen
ExcelFile.open();
//Sheet wählen
ExcelFile.aktivsheet = "Tabelle1";
//Zeile auslesen
String zelle1 = ExcelFile.Zelle(1, 1).Value2;
//Workbook schließen
ExcelFile.close();
//Applikation schließen
EApp.Dispose();

Tipp: Schaltet die automatische Berechnung von Zellen ab und erst kurz vorm speichern wieder an. Das spart oftmals wertvolle Rechenzeit :)

Page 1 of 11
line
footer
Copyright by Neysor | Design based on Elegant Themes