简体   繁体   中英

Data extract from Excel

I am trying to get data by uploading an Excel file. I am using Excel reader in my application which gets the stream and copies the data to the Data table. I need to know why I am getting column0 column1 in the header of dataset when there is no header defined in Excel like that. Or how can I remove the header with column 0 column 1 column 2 column 4 etc. heading the first header in data set from the Excel file. I have added two images one is Excel and one is dataset which grabs Excel data but column 0 column 1 etc. are shown how to remove it.

Stream stream = file.InputStream;
IExcelDataReader reader = null;

if (file.FileName.EndsWith(".xls"))
{
    reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (file.FileName.EndsWith(".xlsx"))
{
    reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
else
{
    ModelState.AddModelError("File", "This file format is not supported");
    return RedirectToAction("Index");
}

DataSet dsresult = reader.AsDataSet();

string filedetails = path + fileName;
FileInfo fileinfo = new FileInfo(filedetails);
if (fileinfo.Exists)
{
    fileinfo.Delete();
}


DataTable dt = new DataTable();
dt = dsresult.Tables[0];
dt.Rows.Remove(dt.Rows[0]);
try
{
    var bl = new BusinessLayer();
    var data = bl.BatchInsert(dt);
    obj = new { resp = data, error = "" };
}
catch (Exception ex)
{
    Logger.Error(ex.Message);
    obj = new { resp = "", error = ex.Message.ToString() };
}

dt = null;

You need to specify that the first row is the header:

DataSet dsresult = reader.AsDataSet(new ExcelDataSetConfiguration() {
    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration() {
        // Gets or sets a value indicating whether to use a row from the 
        // data as column names.
        UseHeaderRow = true         
    }
});

Check the Github page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM