【发布时间】:2019-06-18 08:38:43
【问题描述】:
在我的 Windows 窗体应用程序中加载 Excel 文件时,我可以正常加载 .xls 和 .xlsx 格式,但是当我选择 .CSV 时出现以下错误:
System.NullReferenceException: '对象引用未设置为对象的实例。' sConnectionString 为空。
错误发生就行了:
if (sConnectionString.Length > 0)
来自完整的代码部分:
public string sConnectionString;
public void FillData()
{
if (sConnectionString.Length > 0)
{
OleDbConnection cn = new OleDbConnection(sConnectionString);
{
cn.Open();
DataTable dt = new DataTable();
OleDbDataAdapter Adpt = new OleDbDataAdapter("select * from [sheet1$]", cn);
Adpt.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
在按钮代码之前:
private void Browse_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.InitialDirectory = @"C:\";
op.Title = "Browse Excel Files";
op.CheckFileExists = true;
op.CheckPathExists = true;
op.DefaultExt = "csv";
op.Filter = "CSV Files (*.csv)|*.csv";
op.FilterIndex = 2;
op.RestoreDirectory = true;
op.ReadOnlyChecked = true;
op.ShowReadOnly = true;
if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (File.Exists(op.FileName))
{
string[] Arr = null;
Arr = op.FileName.Split('.');
if (Arr.Length > 0)
{
if (Arr[Arr.Length - 1] == "xls")
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
op.FileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
}
else if (Arr[Arr.Length - 1] == "xlsx")
{
sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + op.FileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
}
}
FillData();
fileTextBox.Text = op.FileName;
}
}
编辑
添加:
else if (Arr[Arr.Length - 1] == "csv")
{
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + op.FileName +
";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
}
还是同样的错误。
【问题讨论】:
-
在您的点击处理程序中,您在两个位置设置
sConnectionString,一个是您的分割片段是“xls”,另一个是“xlsx”。你不要设置它,否则。但是在您的FillData方法中,您检查它的长度(它会触发 NRE)。考虑使用System.IO.Path类中的方法而不是string.Split来挑选路径 -
你安装了微软office吗? ACE 驱动程序附带办公室。如果您没有 Office,则必须从 msdn 安装 ACE。我从来没有成功安装过 ACE,但其他人声称它可以工作。
-
我有点惊讶“xlsx”的工作原理。你的 if/then/else 逻辑搞砸了。进行“xlsx”检查的唯一方法是
Arr.Length是否 else if 应该抛出。你有没有用调试器一步步完成这个? -
@Jimi 我会用 csv 做什么?我已经尝试过 ACE 和 JET 提供程序
-
@jdweng 是的,我已经安装了。
标签: c# excel winforms csv openfiledialog