12

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];
    }
}
}
Community
  • 1
  • 1
Jeremy22
  • 133
  • 1
  • 1
  • 5

2 Answers2

26

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.

user8728340
  • 646
  • 5
  • 7
0

Your file is not in the correct format. Open your file in Microsoft Office and "Save as" again in '.xls' format and use this new file.

MAXE
  • 4,978
  • 2
  • 45
  • 61