C# :: Aufgabe #263 :: Lösung #1
4 Lösungen
#263
Zelle aus Exceldatei auslesen
Anfänger - C#
von Gustl
- 12.06.2019 um 10:29 Uhr
Es solle eine Excel Datei eingelesen (XLSX) und dann ein bestimmter Inhalt einer Zelle wieder ausgegeben werden.
#1
von crazyfrien (80 Punkte)
- 19.06.2019 um 16:00 Uhr
C#-Code
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; //Need to add the Microsoft Office XX.X Object Library at COM namespace ReadExcel { public partial class Form1 : Form { string filePath =""; Excel.Application app; Excel.Workbook workBook; Excel.Worksheet workSheet; string[,] tableContents; public Form1() { InitializeComponent(); app = new Excel.Application(); } private void button1_Click(object sender, EventArgs e) { //Choose File via Dialog openFileDialog1.ShowDialog(); filePath = openFileDialog1.FileName; textBox1.Text = filePath; //Read file workBook = app.Workbooks.Open(filePath); workSheet = workBook.Worksheets[1]; //Show how many items are available int s=1, z = 1; while (workSheet.Cells[z,s].Value != null) { while (workSheet.Cells[z,s].Value != null) { s++; } z++; } s--; //Create array and write contents inside array tableContents = new string[s,z]; for(int i=0;i<tableContents.GetLength(0);i++) { for(int j=0;j<tableContents.GetLength(1);j++) { tableContents[i, j] = workSheet.Cells[j+1, i+1].Value; } } //Write to richtTextBox1 richTextBox1.Clear(); if (textBox2.Text != "" || textBox3.Text != "") { try { richTextBox1.Text = tableContents[Convert.ToInt32(textBox2.Text)-1, Convert.ToInt32(textBox3.Text)-1]; } catch(IndexOutOfRangeException ex) { richTextBox1.Text = "Empty"; } catch(Exception ex) { richTextBox1.Text = ex.Message; } } else { for (int i = 0; i < tableContents.GetLength(1); i++) { for (int j = 0; j < tableContents.GetLength(0); j++) { richTextBox1.Text += tableContents[j, i] + "\t"; } richTextBox1.Text += "\n"; } } } } }
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1