I am importing excel sheet to DataTable using oledb connection as below.
private static DataTable UploadExcelSheet(string fileName)
{
DataTable uploadDataTable;
using (OleDbConnection objXConn = new OleDbConnection())
{
objXConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +
";Extended Properties=\"Excel 12.0;IMEX=1\"";
objXConn.Open();
OleDbCommand objCommand =
new OleDbCommand("SELECT * FROM Template$ ", objXConn);
OleDbDataAdapter objDataAdapter = new OleDbDataAdapter();
// retrieve the Select command for the Spreadsheet
objDataAdapter.SelectCommand = objCommand;
// Create a DataSet
DataSet objDataSet = new DataSet();
// Populate the DataSet with the spreadsheet worksheet data
objDataAdapter.Fill(objDataSet);
uploadDataTable = objDataSet.Tables[0];
}
return uploadDataTable;
}
Everything is working fine but problem comes when user delete content of few rows before uploading the excel. It reads those empty rows as well along with non empty rows, and saving data in database fails because of business rule violation (mandatory field missing). What I tried is putting where condition in query :
"SELECT * FROM WHERE not [CandidateId*] = 0 or not [Firstname*] = '' or not [Lastname] = '' or not [type*] = '' or not [DOB*] =" + DBNull.Value
So it will select only those rows which has data. But I am not able to compare non string field i.e. Date, Integer etc. Which are comming as DBNull when empty. Can any one please suggest the way to do it, I dont want to use DataReader.
How about filtering the rows after the query has executed using Linq to object:
var filteredRows = uploadDataTable.Rows.Cast<DataRow>().Where(
row => row.ItemArray.Any(field => !(field is System.DBNull)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With