Reputation: 1898
In this snippet of code - I get the uploaded file from the user and save it in a folder in my app and then make OleDbConmnection to this Excel File and read the data. My question is - can someone suggest a way which is preferred of reading this excel file but without saving it previously and again as it's in my case fill the datatable with the data
if (Request != null)
{
HttpPostedFileBase file = Request.Files[0];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
string fileExtension = System.IO.Path.GetExtension(Request.Files[0].FileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
string fileLocation = Server.MapPath("~/Content/") + Request.Files[0].FileName;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files[0].SaveAs(fileLocation);
string excelConnectionString = string.Empty;
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
//connection String for xls file format.
if (fileExtension == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
//connection String for xlsx file format.
else if (fileExtension == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", excelConnection);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
DataSet ds = new DataSet();
objAdapter1.Fill(ds);
DataTable Dt = ds.Tables[0];
Upvotes: 0
Views: 9004
Reputation: 104
This line
HttpPostedFileBase file = Request.Files[0];
Say that can't possible convert HttpPostedFile to HttpPostedFileBase
Upvotes: 0
Reputation: 1157
See this library. Excel Data Reader
EDIT example:
if (Request != null)
{
HttpPostedFileBase file = Request.Files[0];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
string fileExtension = System.IO.Path.GetExtension(Request.Files[0].FileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
IExcelDataReader excelReader;
if (fileExtension == ".xls")
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
else
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
DataSet ds = excelReader.AsDataSet();
DataTable Dt = ds.Tables[0];
Upvotes: 4