C# 獲取Excel工作薄中Sheet頁(工作表)名集合
#region 獲取Excel工作薄中Sheet頁(工作表)名集合
/// <summary>
/// 獲取Excel工作薄中Sheet頁(工作表)名集合
/// </summary>
/// <param name="excelFile">Excel文件名及路徑,EG:C:\Users\JK\Desktop\導入測試.xls</param>
/// <returns>Sheet頁名稱集合</returns>
private String[] GetExcelSheetNames(string fileName)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
string connString=string.Empty;
string FileType =fileName.Substring(fileName.LastIndexOf("."));
if (FileType == ".xls")
connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + fileName + ";Extended Properties=Excel 8.0;";
else//.xlsx
connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
// 創建連接對象
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();
}
}
}
#endregion
最後更新:2017-04-03 07:57:16
上一篇:
ScheduledExecutorService和timer的異同
下一篇:
找不到BufferedImage這個Class的解決方法
js中組合使用構造函數模式和原型模式創建對象
magento -- 推薦插件 -- 智能版Js和Css合並 --Lesti::Merge(Smart Merging of Js and Css)
C# 判斷字符串是否可以轉化為數字
Android Fragment中監聽事件
Cmd IIS 重啟
速賣通(aliexpress)活動頁麵優化第二輪,qps大幅提高
【菜鳥翻譯】Creating an Android Project
2014百度校招筆試題之動態鏈接庫&靜態鏈接庫詳解
雲計算與GigaSpaces
獨家專訪 | 獲得軟銀巨額投資的 Mapbox,要如何為自動駕駛提供地圖服務?