C# error With ExcelDataReader
Asked Answered
C

2

13

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];
    }
}
}
Cassandra answered 28/6, 2018 at 9:45 Comment(2)
Are you positive the file your working with in an xls/xlsx/csv file?Dorothi
yes i am @AlexK. it is an xlsx fileCassandra
C
27

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.

Christinachristine answered 2/7, 2018 at 13:58 Comment(0)
B
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.

Broyles answered 30/8, 2021 at 7:21 Comment(1)
This answer has nothing to do with what the OP is askingIntentional

© 2022 - 2024 — McMap. All rights reserved.