[英]how to know which excel sheet is empty using oledb c#?
I'm getting excel sheet name but just the sheet that has data. 我正在获取excel工作表名称,但仅包含数据的工作表。
String fpath = "Provider=Microsoft.ACE.OLEDB.12.0; data source=" +tbpath.Text+ ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
file = new OleDbConnection(fpath);
file.Open();
dt = file.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
//return null;
}
cbsheet.Enabled = true;
//String[] excelSheets = new String[dt.Rows.Count];
//int i = 0;
// Add the sheet name to the string array.
foreach (DataRow row in dt.Rows)
{
if (row["TABLE_NAME"].ToString().Contains("$") )//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
{
cbsheet.Items.Add(row["TABLE_NAME"].ToString());
}
}
//return excelSheets;
}
catch (Exception ex)
{
MessageBox.Show("ERROR: "+ex);
}
You could check each sheet for rows ie 您可以检查每张纸上的行,即
try
{
foreach (DataRow row in dt.Rows)
{
if (row["TABLE_NAME"].ToString().Contains("$") )
{
OleDbCommand cmd = new OleDbCommand(
"select * from [" + row["TABLE_NAME"].ToString() + "]", file);
using (DbDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
cbsheet.Items.Add(row["TABLE_NAME"].ToString());
}
dr.close();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: "+ex);
}
You can just exclude them from getting added. 您可以将它们排除在添加范围之外。
I used this code to filter out empty sheets. 我使用此代码过滤掉了空白纸。 Turns out they are sheets that shouldn't be accessed by the user.
原来它们是用户不应访问的工作表。
You can solve this problem in 2 ways. 您可以通过两种方法解决此问题。
a. 一种。 Ignore them
别管他们
b. b。 Drop down the sheets.
放下床单。
I would highly suggest going with the former. 我强烈建议您选择前者。
Use this code; 使用此代码;
if (!dt.Rows[i]["Table_Name"].ToString().Contains("FilterDatabase") && !dt.Rows[i]["Table_Name"].ToString().EndsWith("$'"))
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.