Forum.
Referencing: https://github.com/ExcelDataReader/ExcelDataReader
C# code :
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}
//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
My code:
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
Debug.WriteLine("OnDragDrop");
if (validData)
{
try
{
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//2. DataSet - The result of each spreadsheet will be created in the result.Tables
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
//3. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}
dataGridView1.DataSource = result.Tables[0];
//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
createEmployees(result);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
My question is, what is the 'Data Reader methods' section used for?
My initial thought was that it was for transforming the data before it was read into the DataSet. From stepping through the code I see that the DataSet result is already set at step 3/4 and thus no transformation or massaging of data has occurred. Given this, I'm not sure what purpose the excelReader.Read() code serves.
This can be used if you do not want to use the DataSet
but read individual rows/columns instead.
Read
sets the reader's cursor to the next row. If there is no more row in the results it returns false
.
So while Read
returns true
, you can read individual columns of the current row:
while(excelReader.Read())
{
int i = excelReader.GetInt32(0); // 0 is the column index in your result set
string text = excelReader.IsDbNull(1) ? string.Empty : excelReader.GetString(1);
// etc...
}
You will need to know the column order in the result set.
Take a look at the documentation of IDataReader
interface and its Get*
methods for more information.