Hi, if I understood you correctly you have a problem here:
if (ws.Cells["F"+riga.ToString()].Value.ToString() != "")
Well the first thing that comes to my mind is that this cell is
null
, so try the following:
ExcelCell cell = ws.Cells["F" + riga.ToString()];
if (cell != null && cell.Value.ToString() != "")
{
Now to add some pointers to your code:
1. You don't have to initialize new
ExcelFile
instance if you are loading an existing excel file. So instead of this:
var ef = new ExcelFile();
ef = ExcelFile.Load(File_Lettura);
Just use this:
var ef = ExcelFile.Load(File_Lettura);
2. You can access each column, row and cell with a name by providing a
string
or with an index by providing an
int
.
In other words, for example instead of this:
int riga = 13;
ws.Cells["B" + riga.ToString()]
You can use this:
int riga = 12;
ws.Columns["B"].Cells[riga];
3. Why are you using
while
loop?
It's much easier and intuitive to iterate through the required group of cell.
For example instead of this:
while (ws.Cells["B"+riga.ToString()].Value != null)
Use something like this:
foreach (ExcelCell cell in ws.Cells.GetSubrange("B13", "B" + ws.Rows.Count))
{
if (cell == null || string.IsNullOrEmpty(cell.Value.ToString()))
continue;
}
4. Last what is
dgwFile
, is it Windows Form's DataGridView control?
In case it is check out
this sample.
It shows how to use
DataGridViewConverter.ExportToDataGridView
and
DataGridViewConverter.ImportFromDataGridView
methods.