C#错误与ExcelDataReader

时间:2018-06-28 09:45:10

标签: c# excel exceldatareader

最近,我试图构建一个可以读取Excel文件的应用。但是就在我选择了excel文件后,我得到一个错误:

  

“ ExcelDataReader.Exceptions.HeaderException”发生在   ExcelDataReader.dll

     

其他信息:无效的文件签名。”

     

该错误在第38行被捕获

这是我的代码的副本

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];
    }
}
}

1 个答案:

答案 0 :(得分:6)

代码调用ExcelReaderFactory.CreateBinaryReader,用于XLS格式。

相反,更改为使用ExcelReaderFactory.CreateOpenXmlReader专门用于XLSX格式,或使用ExcelReaderFactory.CreateReader透明地自动检测XLS或XLSX格式。