读取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);
}
}
}
}
}
}
读取完文件内容之后,显示在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))
{
}
}