C# error With ExcelDataReader

Jeremy22 picture Jeremy22 · Jun 28, 2018 · Viewed 14k times · Source

Recently I was trying to build an app that can read excel files. But just after I select the excel file I get an error saying this:

'ExcelDataReader.Exceptions.HeaderException' occurred in ExcelDataReader.dll

Additional information: Invalid file signature."

The error is caught on line 38

here is a copy of my code

using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Alt_jde
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void label1_Click(object sender, EventArgs e)
    {

    }
    DataSet result;
    private void btnOpen_Click(object sender, EventArgs e)
    {
        using(OpenFileDialog ofd = new OpenFileDialog() )
        {
            if (ofd.ShowDialog()==DialogResult.OK)
            {
                System.IO.FileStream fs = System.IO.File.Open(ofd.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fs);   // ERROR HERE
                var result = reader.AsDataSet(new ExcelDataSetConfiguration()
                {
                    ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                    {
                        UseHeaderRow = true
                    }
                });
                cbosheet.Items.Clear();
                foreach (DataTable dt in result.Tables)
                    cbosheet.Items.Add(dt.TableName);
                reader.Close();
                    }
        }
    }

    private void cbosheet_SelectedIndexChanged(object sender, EventArgs e)
    {
        dataGridView.DataSource = result.Tables[cbosheet.SelectedIndex];
    }
}
}

Answer

user8728340 picture user8728340 · Jul 2, 2018

The code calls ExcelReaderFactory.CreateBinaryReader which is for the XLS format.

Instead, change to use ExcelReaderFactory.CreateOpenXmlReader for the XLSX format specifically, or use ExcelReaderFactory.CreateReader to autodetect either XLS or XLSX formats transparently.