public static void OpenFile()
{
Excel excel = new Excel(@"Testblatt.xlsx",1);
for (int i = 0; i < Excel.cntRow; i )
{
for (int j = 0; j < Excel.cntCln; j )
{
excel.ReadCell(i,j);
MessageBox.Show(excel.ReadCell(i, j));
}
}
excel.wb.Close();
}
In the code at the top you can see cntRow and cntCln which should be the maximum amount of Rows and Columns used in an Excel Spreadsheet, well the IDE tells me that those to variables arent implented right now. The code below is the complete Class where you can see how I implemented it. I am just a beginner so please dont be too harsh to me.
internal class Excel
{
string path = "";
_Application excel = new _Excel.Application();
Workbook wb;
Worksheet ws;
public Excel(string path, int Sheet)
{
this.path = path;
this.wb = excel.Workbooks.Open(path);
this.ws = wb.Worksheets[Sheet];
Range usedRange = ws.UsedRange;
int cntRow = usedRange.Rows.Count;
int cntCln = usedRange.Columns.Count;
}
public string ReadCell(int i, int j)
{
i ;
j ;
if (ws.Cells[i,j].Value2 != null)
return Convert.ToString(ws.Cells[i,j].Value);
else
return "";
}
//lese festgelegte Exceldatei komplett
public static void OpenFile()
{
Excel excel = new Excel(@"Testblatt.xlsx",1);
for (int i = 0; i < Excel.cntRow; i )
{
for (int j = 0; j < Excel.cntCln; j )
{
excel.ReadCell(i,j);
MessageBox.Show(excel.ReadCell(i, j));
}
}
excel.wb.Close();
}
public static void ConView()
{
OpenFile();
}
}
CodePudding user response:
You are doing two things wrong. First of all Excel is the name of your class, your instance is called excel, that's the one you need to use. Second, you are not publishing the properties of cntCln and cntRow, so they aren't visible outside your class.
Change your class like this:
internal class Excel
{
string path = "";
_Application excel = new _Excel.Application();
Workbook wb;
Worksheet ws;
private int cntRow;
private int cntCln;
public Excel(string path, int Sheet)
{
this.path = path;
this.wb = excel.Workbooks.Open(path);
this.ws = wb.Worksheets[Sheet];
Range usedRange = ws.UsedRange;
cntRow = usedRange.Rows.Count;
cntCln = usedRange.Columns.Count;
}
public int CntCln => cntCln;
public int CntRow => cntRow;
...
And use it like this:
public static void OpenFile()
{
Excel excel = new Excel(@"Testblatt.xlsx",1);
for (int i = 0; i < excel.CntRow; i )
{
for (int j = 0; j < excel.CntCln; j )
{
excel.ReadCell(i,j);
MessageBox.Show(excel.ReadCell(i, j));
}
}
excel.wb.Close();
}
And the days of FORTRAN76 are long gone. You may use more that 6 characters for a variable name. In fact, in the long run, it's much better to have properties named RowCount and ColumnCount instead of CntRow and CntCln.