I am trying to write an app that reads from an Excel file and displays information on a Windows form app. This is my code (this is taken straight from this video: https://www.youtube.com/watch?v=lsv7rAsvYuA)
Main form:
public partial class Form1 : Form
{
int i = 1;
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
Reader excel = new Reader("C:/Users/marti/Desktop/minput.xlsm", 1);
lbMain.Items.Add(excel.ReadCell(i, 1));
i++;
}
}
Reader class:
class Reader
{
string path = "";
_Application excel = new _Excel.Application();
Workbook wb;
Worksheet ws;
public Reader(string path, int sheet)
{
this.path = path;
wb = excel.Workbooks.Open(path);
ws = wb.Worksheets[sheet];
}
public string ReadCell(int row, int col)
{
if (ws.Cells[row, col].Value2 != null)
{
return ws.Cells[row, col].Value2;
}
else
{
return "";
}
}
}
Pressing the button freezes the app for about 5 seconds, before finally unfreezing and displaying the information in the listbox. I first thought that it would only happen on the first button click, as that's when the file is being loaded. However, it happens on every consecutive click too.
The freezing seems to be worse with larger Excel sheets.
Advice?