[英]Error reading Excel document in forms C#
我正在嘗試獲取XLSX數據,並使用ExcelDataReader NuGet包將其放入DataGridView中。 但是我在第35行上得到了未設置為對象錯誤實例的對象引用
foreach (DataTable dt in result.Tables)
這是完整的代碼。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using Excel;
namespace MyForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet result;
private void butOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fs);
reader.IsFirstRowAsColumnNames = true;
result = reader.AsDataSet();
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];
}
}
}
這是錯誤消息: 錯誤
針對評論:
屬性IsFirstRowAsColumnNames
在該軟件包的較新版本上不再可用。
從GitHub頁面LINK :
AsDataSet配置選項
AsDataSet()函數接受一個可選的配置對象,以修改DataSet轉換的行為:
var result = reader.AsDataSet(new ExcelDataSetConfiguration() {
// Gets or sets a value indicating whether to set the DataColumn.DataType
// property in a second pass.
UseColumnDataType = true,
// Gets or sets a callback to obtain configuration options for a DataTable.
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration() {
// Gets or sets a value indicating the prefix of generated column names.
EmptyColumnNamePrefix = "Column",
// Gets or sets a value indicating whether to use a row from the
// data as column names.
UseHeaderRow = false,
// Gets or sets a callback to determine which row is the header row.
// Only called when UseHeaderRow = true.
ReadHeaderRow = (rowReader) => {
// F.ex skip the first row and use the 2nd row as column headers:
rowReader.Read();
}
}
});
我猜這行UseHeaderRow = true;
在ExcelDataTAbleConfiguration
中將導致所需的行為。
編輯:添加工作示例
本示例為我使用在Excel 2016中創建的新.xlsx文件為我工作。該文件包含兩張紙:工作表1和工作表2。兩者都包含兩列,兩行文本。
List<string> tblNames = new List<string>();
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() ?? false)
{
using (FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(fs))
{
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
UseColumnDataType = true,
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
foreach (DataTable dt in result.Tables)
tblNames.Add(dt.TableName);
}
}
}
這是WPF應用程序,因此OpenFileDialog
的用法看起來有些不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.