Вы можете попробовать следующий код, чтобы показать имя листа, исключая пустой лист.
Код:
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;
}
}
Результат:
введите описание изображения здесь