c#读取Excel文件后报错

问题遇到的现象和发生背景

读取Excel文件,本地选择文件之后报错
System.NotSupportedException
HResult=0x80131515
Message=No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.

    private void button1_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = @"Excel表格|*.xlsx|Excel|*.xls" })
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtFilename.Text = openFileDialog.FileName;
                using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
                {
                    using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
                    {
                        DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
                        {
                            ConfigureDataTable = (_) => new ExcelDataTableConfiguration() { UseHeaderRow = true }
                        });
                        tableCollection = result.Tables;
                        cboSheet.Items.Clear();
                        foreach (DataTable item in tableCollection)
                        {
                            cboSheet.Items.Add(item.TableName);
                        }
                    }
                }
            }
        }
    }
运行结果及报错内容

img

我的解答思路和尝试过的方法
我想要达到的结果

读取完文件内容之后,显示在dataGridView组件内

参考:

I faced the same problem with .net Core application. I added the System.Text.Encoding.CodePages nuget package and registered the encoding provider before ExcelReaderFactory.CreateReader(stream) which resolved the issue.


System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
//open file and returns as Stream
using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
      using (var reader = ExcelReaderFactory.CreateReader(stream))
      {
      }
}

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632