尝试读取XLSM文件并从2列中提取数据。我的c#应用程序中包含以下代码,但似乎无法正常工作,datagridview从不显示任何数据,当我遍历代码时,到达连接字符串行,没有错误,也没有任何显示。
我找到了一些excel的OLE连接字符串示例,但是没有用,下面是我尝试过的最新代码。
关于我在做什么错或我还能尝试什么的任何建议?
public string ConnectionString(string FileName, string Header)
{
OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
if (System.IO.Path.GetExtension(FileName).ToUpper() == ".XLSM")
{
Builder.Provider = "Microsoft.Jet.OLEDB.4.0";
Builder.Add("Extended Properties", string.Format("Excel 8.0;IMEX=1;HDR={0};", Header));
}
else
{
Builder.Provider = "Microsoft.ACE.OLEDB.12.0";
Builder.Add("Extended Properties", string.Format("Excel 12.0;IMEX=1;HDR={0};", Header));
}
Builder.DataSource = FileName;
return Builder.ConnectionString;
}
public DataTable LoadData(string FileName)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
DataTable dt = new DataTable();
using (OleDbConnection cn = new OleDbConnection { ConnectionString = ConnectionString(FileName, "No") })
{
cn.Open();
using (OleDbCommand cmd = new OleDbCommand { CommandText = "SELECT F2 As Parent, E2 As Gender FROM [Data$A2:I300]", Connection = cn })
{
OleDbDataReader dr = cmd.ExecuteReader();
dt.Load(dr);
}
return dt;
}
}
private void excelParents_Load(object sender, EventArgs e)
{
string fn = @"C:\Temp\Template.xlsm";
dgvParentListing.DataSource = LoadData(fn);
}
在这一点上,我只是希望在表单上的datagridview控件中看到表单中的数据。但是它的空白,一旦表单加载,我就没有错误