Visual Studio 19 Xaml C# Excel Dateien erstellen

  • VB.NET

Es gibt 12 Antworten in diesem Thema. Der letzte Beitrag () ist von MrLaTuNiX.

    Visual Studio 19 Xaml C# Excel Dateien erstellen

    Hey, ich bin neu am programmieren und meine frage ist wie schaffe ich es neue Excel Tabellen zu speichern. Mein Programm ist so ein Benutzer log sich ein und dann muss er bestimmte Daten x eingeben und muss am ende auf speichern klicken und dann soll eine neue Excel Tabelle erzeugt werden mit den Daten in einen Ordner, so das man immer auf die Excel Tabellen zugriff hat. Die frage ist für mich wie schaffe ich es immer neue Excel Tabellen anzulegen irgendwie kriege ich es nicht und ein kleines Test Beispiel würde mir schon reichen.

    *Thema aus WPF Bereich verschoben* ~NoFear23m

    Dieser Beitrag wurde bereits 2 mal editiert, zuletzt von „VaporiZed“ ()

    Ich hab da nochmal was um epplus gebau:
    Der ansatz ist, das du Als erstest dein ExcelFIle lädst und dann deine Tabellen
    Die Tabellen musst du als Class Anglegen und von ExcelTable erben lassen

    Dann nutzt du den Ctor "public ExcelTable(ExcelDocument excel, string sheet)" und überlädst den....
    Wenn du hilfe brauchst, schreib oder was auch immer :P

    Column:
    Spoiler anzeigen

    C#-Quellcode

    1. class Column
    2. {
    3. private readonly ExcelTable _table;
    4. public readonly int ColumnIndex;
    5. public string this[int row]
    6. {
    7. get => _table[row, ColumnIndex].ToString2();
    8. set => _table[row, ColumnIndex] = value;
    9. }
    10. public Column(ExcelTable excel, int columnIndex)
    11. {
    12. _table = excel;
    13. ColumnIndex = columnIndex;
    14. }
    15. public Column GetNextColumn()
    16. {
    17. int nextColumnIndex = ColumnIndex + 1;
    18. if (nextColumnIndex >= _table.Columns)
    19. throw new IndexOutOfRangeException(nameof(nextColumnIndex));
    20. return new Column(_table, nextColumnIndex);
    21. }
    22. }


    ExcelDocument :
    Spoiler anzeigen

    C#-Quellcode

    1. class ExcelDocument : IDisposable
    2. {
    3. private readonly FileInfo _filePath;
    4. private readonly ExcelPackage _app;
    5. public ExcelWorkbook Workbook { get; private set; }
    6. internal ExcelDocument(ExcelDocument document)
    7. {
    8. _filePath = document._filePath;
    9. _app = document._app;
    10. Workbook = document.Workbook;
    11. }
    12. public ExcelDocument(string path)
    13. {
    14. _filePath = new FileInfo(path);
    15. if (_filePath.Exists)
    16. {
    17. _app = new ExcelPackage(_filePath);
    18. }
    19. else
    20. {
    21. _app = new ExcelPackage();
    22. }
    23. try
    24. {
    25. Workbook = _app.Workbook;
    26. }
    27. catch
    28. {
    29. _app.Dispose();
    30. }
    31. }
    32. public void CreateWorksheet(string name)
    33. {
    34. // todo check
    35. Workbook.Worksheets.Add(name);
    36. }
    37. public void Update()
    38. {
    39. Save();
    40. }
    41. public void Save()
    42. {
    43. _app.SaveAs(_filePath);
    44. }
    45. public void Dispose()
    46. {
    47. _app?.Dispose();
    48. }
    49. }

    ExcelTable :
    Spoiler anzeigen

    C#-Quellcode

    1. class ExcelTable : ExcelDocument
    2. {
    3. public ExcelWorksheet Sheet { get; protected set; }
    4. public ExcelAddressBase Dimension => Sheet.Dimension;
    5. public int Rows => Dimension.Rows;
    6. public int Columns => Dimension.Columns;
    7. public object this[int row, int column]
    8. {
    9. get => Sheet.Cells[row, column].Value.ToString2();
    10. set => Sheet.Cells[row, column].Value = value;
    11. }
    12. public string this[int row, int column, string @default]
    13. {
    14. get => Sheet.Cells[row, column].ToStringOrDefault(@default);
    15. }
    16. public object this[int row]
    17. {
    18. get => new object[Columns].Select((col, iCol) => Sheet.Cells[row, iCol]).ToArray();
    19. }
    20. public ExcelRange this[int fromRow, int fromCol, int toRow, int toCol]
    21. {
    22. get => Sheet.Cells[fromRow, fromCol, toRow, toCol];
    23. }
    24. public ExcelRange this[string addess]
    25. {
    26. get => Sheet.Cells[addess];
    27. }
    28. public ExcelTable(ExcelDocument excel, string sheet)
    29. : base(excel)
    30. {
    31. Sheet = excel.Workbook.Worksheets[sheet];
    32. if (Sheet == null)
    33. {
    34. Sheet = excel.Workbook.Worksheets.Add(sheet);
    35. Sheet.Name = sheet;
    36. }
    37. }
    38. public Column GetColumn(Regex regularExpression, Func<ExcelTable, Match, int, Column> func)
    39. {
    40. for (int iCol = 0; iCol < Columns; iCol++)
    41. {
    42. return func(this, regularExpression.Match(this[0, iCol].ToString2()), iCol);
    43. }
    44. throw new Exception("Column not found");
    45. }
    46. public Column GetColumn(int scanRow, Regex regularExpression, Func<ExcelTable, Match, int, Column> func)
    47. {
    48. for (int iCol = 0; iCol < Columns; iCol++)
    49. {
    50. return func(this, regularExpression.Match(this[scanRow, iCol].ToString2()), iCol);
    51. }
    52. throw new Exception("Column not found");
    53. }
    54. public IEnumerable<TOut> GetColumns<TOut>(Regex regularExpression, Func<ExcelTable, Match, int, TOut> func) where TOut : Column
    55. {
    56. for (int iCol = 0; iCol < Columns; iCol++)
    57. {
    58. yield return func(this, regularExpression.Match(this[0, iCol].ToString2()), iCol);
    59. }
    60. }
    61. public IEnumerable<TOut> GetColumns<TOut>(Regex regularExpression, int scanRow, Func<ExcelTable, Match, int, TOut> func) where TOut : Column
    62. {
    63. for (int iCol = 0; iCol < Columns; iCol++)
    64. {
    65. yield return func(this, regularExpression.Match(this[scanRow, iCol].ToString2()), iCol);
    66. }
    67. }
    68. public Column GetColumn(string name)
    69. {
    70. for (int i = 0; i < Columns; i++)
    71. {
    72. if (this[0, i].ToString2() == name)
    73. {
    74. return new Column(this, i);
    75. }
    76. }
    77. throw new Exception("Column not found");
    78. }
    79. public Column GetColumn(string name, int scanStart)
    80. {
    81. if (scanStart < 0)
    82. throw new ArgumentOutOfRangeException(nameof(scanStart) + " must be bigger or equals to 0");
    83. if (scanStart >= Columns)
    84. throw new ArgumentOutOfRangeException(nameof(scanStart));
    85. for (int i = scanStart; i < Columns; i++)
    86. {
    87. if (this[0, i].ToString2() == name)
    88. {
    89. return new Column(this, i);
    90. }
    91. }
    92. throw new Exception("Column not found");
    93. }
    94. public Column GetColumn(string name, int scanStart, int scanEnd)
    95. {
    96. if (scanStart < 0)
    97. throw new ArgumentOutOfRangeException(nameof(scanStart) + " must be bigger or equals to 0");
    98. if (scanEnd < 0)
    99. throw new ArgumentOutOfRangeException(nameof(scanEnd) + " must be bigger or equals to 0");
    100. if (scanStart >= Columns)
    101. throw new ArgumentOutOfRangeException(nameof(scanStart));
    102. if (scanEnd >= Columns)
    103. throw new ArgumentOutOfRangeException(nameof(scanEnd));
    104. if (scanEnd <= scanStart)
    105. throw new Exception(nameof(scanEnd) + " musst be smaller then " + nameof(scanStart));
    106. for (int i = scanStart; i < Columns; i++)
    107. {
    108. if (this[0, i].ToString2() == name)
    109. {
    110. return new Column(this, i);
    111. }
    112. }
    113. throw new Exception("Column not found");
    114. }
    115. public Column GetColumn(string name, Func<string, string, bool> compare)
    116. {
    117. for (int i = 0; i < Columns; i++)
    118. {
    119. if (compare(this[0, i].ToString2(), name))
    120. {
    121. return new Column(this, i);
    122. }
    123. }
    124. throw new Exception("Column not found");
    125. }
    126. public Column GetColumn(int scanRow, string name, Func<string, string, bool> compare)
    127. {
    128. for (int i = 0; i < Columns; i++)
    129. {
    130. if (compare(this[scanRow, i].ToString2(), name))
    131. {
    132. return new Column(this, i);
    133. }
    134. }
    135. throw new Exception("Column not found");
    136. }
    137. public Column GetColumn(int scanRow, string name)
    138. {
    139. for (int i = 0; i < Columns; i++)
    140. {
    141. if (this[scanRow, i].ToString2().StartsWith(name))
    142. {
    143. return new Column(this, i);
    144. }
    145. }
    146. throw new Exception("Column not found");
    147. }
    148. public Column GetColumn(int scanRow, string name, int scanStart)
    149. {
    150. if (scanStart < 0)
    151. throw new ArgumentOutOfRangeException(nameof(scanStart) + " must be bigger or equals to 0");
    152. if (scanStart >= Columns)
    153. throw new ArgumentOutOfRangeException(nameof(scanStart));
    154. for (int i = scanStart; i < Columns; i++)
    155. {
    156. if (this[scanRow, i].ToString2().StartsWith(name))
    157. {
    158. return new Column(this, i);
    159. }
    160. }
    161. throw new Exception("Column not found");
    162. }
    163. public Column GetColumn(int scanRow, string name, int scanStart, int scanEnd)
    164. {
    165. if (scanStart < 0)
    166. throw new ArgumentOutOfRangeException(nameof(scanStart) + " must be bigger or equals to 0");
    167. if (scanEnd < 0)
    168. throw new ArgumentOutOfRangeException(nameof(scanEnd) + " must be bigger or equals to 0");
    169. if (scanStart >= Columns)
    170. throw new ArgumentOutOfRangeException(nameof(scanStart));
    171. if (scanEnd >= Columns)
    172. throw new ArgumentOutOfRangeException(nameof(scanEnd));
    173. if (scanEnd <= scanStart)
    174. throw new Exception(nameof(scanEnd) + " musst be smaller then " + nameof(scanStart));
    175. for (int i = scanStart; i < Columns; i++)
    176. {
    177. if (this[scanRow, i].ToString2().StartsWith(name))
    178. {
    179. return new Column(this, i);
    180. }
    181. }
    182. throw new Exception("Column not found");
    183. }
    184. public Column GetColumn(int index)
    185. {
    186. return new Column(this, index);
    187. }
    188. }

    ObjectExtension:
    Spoiler anzeigen

    C#-Quellcode

    1. static class ObjectExtension
    2. {
    3. public static string ToStringOrDefault(this object obj, string @default)
    4. {
    5. if (obj == null)
    6. {
    7. return @default;
    8. }
    9. if (obj is string value)
    10. {
    11. return value;
    12. }
    13. return @default;
    14. }
    15. public static string ToString2(this object obj)
    16. {
    17. if (obj == null)
    18. {
    19. return string.Empty;
    20. }
    21. if (obj is string value)
    22. {
    23. return value;
    24. }
    25. return obj.ToString();
    26. }
    27. }

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „Facebamm“ ()

    @Facebamm: Eine gesonderte Klassenstruktur als Rahmen könnte einen Anfänger erschlagen.
    Zumal das in C# ist.
    Und er gar keine Excel-Datei hat, sondern aus seinen Daten eine neue erzeugen will.

    Zwar auch in C#, aber leicht verständlich und 1:1 in VB.Net konvertierbar ist dieses Beispiel:
    c-sharpcorner.com/blogs/how-to…pplus-net-library-c-sharp
    --
    If Not Program.isWorking Then Code.Debug Else Code.DoNotTouch
    --
    C# ist doch richtig Oo ... ja, wenn er es möchte, kann er es nutzen, ist ja kein muss :D
    Wobei ich find es eher sogar simpler als das reine EPPlus, weil ich hab mein ExcelDocument, davon entnehm ich mein Tabellen(ExcelTable) und kann davon aus mein Spalten klar benennen. :D
    Es ist nur etwas definierter und ich muss nicht mit indexen umher werfen :D
    Kontra: Ja, ich könnte auch Konstanten nutzen ... :saint:

    Und fragen wie, "Wie nutz ich das nun?" beantworte ich auch gern :D
    Ich hab 4 neu Klassen angelegt.
    Ich hab mir ein eingenes Projekt gepackt "EPPlusEasy"und dort die 4 Klassen erstellt.
    Kannst aber auch nen Ordner machen in deinem Projekt und dort die 4 Klassern erstellen


    Du musst aber das Nuget "EPPlus" installieren wie es @petaod vorgeschlagen hast !! Version 4, nicht die 5 weil das Lizen änderungen gab !!

    Hier ist mal ein kleines Anwendungsbeispiel :D

    Spoiler anzeigen


    C#-Quellcode

    1. class Program
    2. {
    3. static void Main(string[] args)
    4. {
    5. // wichtig in excel wird alles ab 1 gezählt!!
    6. using (ExcelDocument excelFile = new ExcelDocument("Example.xlsx"))
    7. {
    8. Preise preise = new Preise(excelFile);
    9. string id = preise.ID[2 /*zeile der spalte */];
    10. string preis = preise.Preis[2 /*zeile der spalte */];
    11. }
    12. }
    13. }
    14. class Preise : ExcelTable
    15. {
    16. public const string TABLE_NAME = "Preise";
    17. /// <summary>
    18. /// Erste Spalte
    19. /// </summary>
    20. public Column ID { get; }
    21. /// <summary>
    22. /// Zweite Spalte
    23. /// </summary>
    24. public Column Preis { get; }
    25. public Preise(ExcelDocument excel) : base(excel, TABLE_NAME)
    26. {
    27. ID = GetColumn("ID"); // Spalte mittels namen ermitteln (1 Zeile)
    28. Preis = GetColumn(2); // Spalte per index
    29. }
    30. }

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „Facebamm“ ()

    okay soweit verstanden eine frage iczh mache das in Xaml das sollte aber kein unterschied machen richtig ?
    und um es besser zu sagen ich hab ja ein window mit einem button und wenn ich auf den button drauf klicke soll sich eine neue excel tabelle erstellen

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „MrLaTuNiX“ ()

    Und um es besser zu sagen ich hab ja ein window mit einem button und wenn ich auf den button drauf klicke soll sich eine neue excel tabelle erstellen wie verbinde ich das in meiner main klasse ?(will hier ein screenshot reinfügen wie macht man das ? sorry bin halt neu :/)
    Also im prinzip bleibt alles wie oben im screenshot, denn das base() beim Konstrutor leitet dich weiter in die Klasse "ExcelTable" zum Konstruktor

    C#-Quellcode

    1. public ExcelTable(ExcelDocument excel, string sheet)
    2. : base(excel)
    3. {
    4. Sheet = excel.Workbook.Worksheets[sheet];
    5. if (Sheet == null)
    6. {
    7. Sheet = excel.Workbook.Worksheets.Add(sheet);
    8. Sheet.Name = sheet;
    9. }
    10. }


    der schaut ob er eine Tabelle/Reiter mit dem Name findet, wenn nicht wird eine Tabelle/Reiter mit dem Name.


    Wenn du Spalten(Column) erstellt dann musst du hier naturlich über den index gehen wie im Bsp. Zeile 32 (Preis = GetColumn(2);)

    Schrieben tust du indem du Preis[zeilenIndex] = Wert; aufruft.

    Am ende darfst du das speicher nicht vergessen

    excelFile.Save();
    Aso mein Fehler war auch das du das in einer Console geschrieben hast und ich das nicht verstanden hab, wie gesagt bin neu aber arbeite mich grad rein und so langsam funktioniert es :D
    Nur um es besser zu erläutern ich habe in meinen Programm einen Button und wenn ich darauf klicke dann erstellt er mir eine neue Excel Datei mit den Sachen die ich in mehreren textboxen eingebe
    Also kannst du nachvollziehen was ich will ? weil musste den ganzen tag erstmal mir dein Programm angucken damit ich dahinter komme und zu 100 % verstehe ich noch nicht alles aber vieles
    und bis hier hin ein danke von mir das mir das alles so gibst :)