Fragensteller
Lesen und schreiben aus einer Excel-Datei (NPOI)

Allgemeine Diskussion
-
Hallo,
ich bin hier und in dem Bereich der C#-Programmierung noch sehr neu und stehe einem Problem, weshalb ich mich an euch wende.
Ich will aus einer Excel- und XML-Datei lesen. Darin Inhalte vergleichen und in die gleiche oder Alternativerweise in eine andere Excel-Datei raus schreiben.
Das Grundgerüst für den Code besteht bereits und das Auslesen der XML-Datei hat soweit geklappt. Im nächsten Schritt wollte ich aus der Excel-Datei mithilfe von NPOI Werte auslesen (3 Spalten und immer unterschiedliche Zeilenanzahl) woran ich jedoch leider nicht weiter komme. Wollte diese in ein Array schreiben etwas abändern und wieder raus schreiben.
Bevor ich das nicht hinbekomme, kann ich leider mit nichts anderem fortfahren. Daher die Frage was in dem Code falsch ist bzw. wo noch was hinzufügen muss?
Steht const string fileName an der richtigen Stelle?
Muss ich ReadExcel und WriteExcel noch im Main aufrufen?Steh da leider etwas aufm Schlauch und bin für jede Hilfe dankbar :)
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.Xml; using Excel = Microsoft.Office.Interop.Excel; namespace Converter { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { const string fileName = @"N:\Dokumente\Bachelorarbeit\Dateien\Converter - Kopie\Converter\bin\Debug\Testdatei.xls"; public MainWindow() { InitializeComponent(); //Read xml and fill dict XmlTextReader reader = new XmlTextReader("variablegroups.xml"); string string_xml = ""; string str1 = "ecatSource"; string str2 = "name"; bool inout = false; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: string_xml = reader.Name; break; case XmlNodeType.Text: if (string_xml.Equals(str1)) { inout = true; } if ((string_xml.Equals(str1) || string_xml.Equals(str2)) && inout) { Console.Write(reader.Value); //write value Console.Write("\n"); if (string_xml.Equals(str2)) { inout = false; } } break; } } Console.ReadLine(); //Example for variables from XML //VarSymbolicDic.Add("-184K1 (CPX-FB38 64Byte).Outputs.QB2.Bit07","Run In Turntable Brake-High pressure"); //VarSymbolicDic.Add("-184K1 (CPX-FB38 64Byte).Outputs.QB2.Bit08","Run In Turntable Brake-High pressure 2"); //Read comment from excel string feecomment = "TIID.Device1.EtherCAT Simulation.-184K1 (CPX-FB38 64Byte).Outputs.QB2.Bit07"; var result = feecomment.Replace("TIID.Device1.EtherCAT Simulation.", ""); List<string> allcomments = new List<string>(); allcomments.Add(result); foreach (string comment in allcomments) { if (VarSymbolicDic.ContainsKey(comment)) { //replace symbolic name in excel } } //write to excel again } //Read Excel public void ReadExcel(string fileName) { using (var file = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { var wb = WorkbookFactory.Create(file); var sheet = wb.GetSheetAt(wb.ActiveSheetIndex); MessageBox.Show("Hallo1"); //Variables.Clear(); foreach (IRow row in sheet) { //Check if it is a TwinCat Excel File var tag = row.GetCell(0)?.ToString() ?? ""; var address = row.GetCell(1)?.ToString() ?? ""; var vartype = row.GetCell(2)?.ToString() ?? ""; var varfullName = row.GetCell(4)?.ToString() ?? ""; var usage = row.GetCell(5)?.ToString() ?? ""; var comment = row.GetCell(6)?.ToString() ?? ""; //Tag = tag, // Address = address, // Type = type, // Path = varfullName, // Usage = usageMode, } wb.Close(); } } //Write result in excel public void WriteExcel(string fileName) { //Create new Excel Workbook var workbook = new HSSFWorkbook(); //Create new Excel Sheet var sheet = workbook.CreateSheet("New Sheet"); //Create a header row var headerRow = sheet.CreateRow(0); headerRow.CreateCell(0).SetCellValue("Symbol"); headerRow.CreateCell(1).SetCellValue("Adress"); headerRow.CreateCell(2).SetCellValue("Type"); headerRow.CreateCell(3).SetCellValue("Comment"); headerRow.CreateCell(4).SetCellValue("VarFullName"); headerRow.CreateCell(5).SetCellValue("Usage"); //(Optional) freeze the header row so it is not scrolled sheet.CreateFreezePane(0, 1, 0, 1); int rowNumber = 1; //Populate the sheet with values from the grid data //Create a new Row var row = sheet.CreateRow(rowNumber++); //Set the Values for Cells row.CreateCell(0).SetCellValue(""); row.CreateCell(1).SetCellValue(""); //Address); row.CreateCell(2).SetCellValue(""); //Type.ToString()); row.CreateCell(3).SetCellValue(""); //Comment); row.CreateCell(4).SetCellValue(""); //.Path)); row.CreateCell(5).SetCellValue(""); //.Usage.ToString())); //Write the Workbook to a memory stream try { FileStream fileOut = new FileStream(fileName, FileMode.Create); workbook.Write(fileOut); fileOut.Flush(); fileOut.Close(); workbook.Close(); } catch (Exception e) { MessageBox.Show(e.Message); } } Dictionary<string,string> VarSymbolicDic = new Dictionary<string, string>(); } }
- Typ geändert Ivan DragovMicrosoft contingent staff, Moderator Mittwoch, 19. Dezember 2018 08:40 Keine Rückmeldung
Alle Antworten
-
Hallo Chris9090,
Du kannst versuchen, NPOI Bibliothek zu verwenden, wie im folgenden Link beschrieben:
C#: Read and Write Excel (*.xls and *.xlsx) Files Content without Excel Automation (using NPOI and ADO.NET)Gruß,
Ivan Dragov
Bitte haben Sie Verständnis dafür, dass im Rahmen dieses Forums, welches auf dem Community-Prinzip „IT-Pros helfen IT-Pros“ beruht, kein technischer Support geleistet werden kann oder sonst welche garantierten Maßnahmen seitens Microsoft zugesichert werden können.