直接上代码

引用


using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;

/// <summary>
/// 获取Excel工作薄中Sheet页(工作表)名集合
/// </summary>
/// <param name=”excelFile”>Excel文件名及路径</param>
/// <returns>Sheet页名称集合</returns>
private String[] GetExcelSheetNames(string fileName, string FileType, bool hasTitle = false)

{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
string connString = string.Empty;
connString = string.Format(“Provider=Microsoft.Jet.OLEDB.{0}.0;” +
“Extended Properties=\”Excel {1}.0;HDR={2};IMEX=1;\”;” +
“data source={3};”,
(FileType == “.xls” ? 4 : 12), (FileType == “.xls” ? 8 : 12), (hasTitle ? “Yes” : “NO”), fileName);
objConn = new OleDbConnection(connString);
// 打开数据库连接
objConn.Open();
// 得到包含数据架构的数据表
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// 添加工作表名称到字符串数组
foreach (DataRow row in dt.Rows)

{
string strSheetTableName = row[“TABLE_NAME”].ToString();
//过滤无效SheetName
if (strSheetTableName.Contains(“$”) && strSheetTableName.Replace(“‘”, “”).EndsWith(“$”))
{
excelSheets[i] = strSheetTableName.Substring(0, strSheetTableName.Length – 1);
}
i++;
}
return excelSheets;
}
catch (Exception ex)

{
MessageBox.Show(ex.ToString());
return null;
}

finally
{
// 清理
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}

}

说点什么
支持Markdown语法
在"C# 获取Excel 工作簿 sheet 列表及名称"已有5条评论
Loading...