Reputation: 141
I am accessing excel workbook in c# application. I am showing the sheet names to user by using list lstSheetsEx
. But I want to exclude the empty sheet before showing to user.
using (OleDbConnection connExcel = new OleDbConnection(DatabaseObjects.ConnectionStringExcel))
{
connExcel.Open();
DataTable dtSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
List<string> lstSheetsEx = dtSchema.AsEnumerable()
.Select(r => r.Field<string>("TABLE_NAME").Trim(new char[] { '\'', '$' })).ToList();
}
Upvotes: 0
Views: 338
Reputation: 5986
You can try the following code to show the sheet name exclude the empty sheet.
Code:
class Program
{
static void Main(string[] args)
{
var list = Checknullsheet("D:\\3.XLSX");
list.ForEach(p => Console.WriteLine(p));
Console.ReadKey();
}
public static List<string> Checknullsheet(string FileName)
{
DataSet set = new DataSet();
int totalSheet = 0; //No of sheets on excel file
using (OleDbConnection objConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"))
{
objConn.Open();
DataTable dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = string.Empty;
List<string> sheetlist = new List<string>();
DataTable table = new DataTable();
if (dt != null)
{
var tempDataTable = (from dataRow in dt.AsEnumerable()
where !dataRow["TABLE_NAME"].ToString().Contains("FilterDatabase")
select dataRow).CopyToDataTable();
dt = tempDataTable;
totalSheet = dt.Rows.Count;
for (int i = 0; i < totalSheet; i++)
{
table = makeDataTableFromSheetName(FileName, dt.Rows[i]["TABLE_NAME"].ToString());
table.TableName = dt.Rows[i]["TABLE_NAME"].ToString();
set.Tables.Add(table);
sheetlist.Add(dt.Rows[i]["TABLE_NAME"].ToString());
}
sheetName = dt.Rows[0]["TABLE_NAME"].ToString();
}
foreach (DataTable item in set.Tables)
{
if(item.Rows.Count<=0)
{
sheetlist.Remove(item.TableName);
}
}
objConn.Close();
return sheetlist; //Returning Dattable
}
}
private static DataTable makeDataTableFromSheetName(string filename, string sheetName)
{
System.Data.OleDb.OleDbConnection myConnection = new System.Data.OleDb.OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0; " +
"data source='" + filename + "';" +
"Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\" ");
DataTable dtImport = new DataTable();
System.Data.OleDb.OleDbDataAdapter myImportCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + sheetName + "]", myConnection);
myImportCommand.Fill(dtImport);
return dtImport;
}
}
Result:
Upvotes: 1