Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# error With ExcelDataReader

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];
    }
}
}
like image 708
Jeremy22 Avatar asked Jun 28 '18 09:06

Jeremy22


1 Answers

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.

like image 172
user8728340 Avatar answered Oct 20 '22 01:10

user8728340