国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

asp.net 讀取Excel數(shù)據(jù)到DataTable的代碼

2024-07-10 12:42:29
字體:
供稿:網(wǎng)友
代碼如下:
/// <summary>
/// 獲取指定路徑、指定工作簿名稱的Excel數(shù)據(jù):取第一個sheet的數(shù)據(jù)
/// </summary>
/// <param name="FilePath">文件存儲路徑</param>
/// <param name="WorkSheetName">工作簿名稱</param>
/// <returns>如果爭取找到了數(shù)據(jù)會返回一個完整的Table,否則返回異常</returns>
public DataTable GetExcelData(string astrFileName)
{
string strSheetName = GetExcelWorkSheets(astrFileName)[0].ToString();
return GetExcelData(astrFileName, strSheetName);
}


代碼
代碼如下:
/// <summary>
/// 返回指定文件所包含的工作簿列表;如果有WorkSheet,就返回以工作簿名字命名的ArrayList,否則返回空
/// </summary>
/// <param name="strFilePath">要獲取的Excel</param>
/// <returns>如果有WorkSheet,就返回以工作簿名字命名的ArrayList,否則返回空</returns>
public ArrayList GetExcelWorkSheets(string strFilePath)
{
ArrayList alTables = new ArrayList();
OleDbConnection odn = new OleDbConnection(GetExcelConnection(strFilePath));
odn.Open();
DataTable dt = new DataTable();
dt = odn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
throw new Exception("無法獲取指定Excel的架構(gòu)。");
}
foreach (DataRow dr in dt.Rows)
{
string tempName = dr["Table_Name"].ToString();
int iDolarIndex = tempName.IndexOf('$');
if (iDolarIndex > 0)
{
tempName = tempName.Substring(0, iDolarIndex);
}
//修正了Excel2003中某些工作薄名稱為漢字的表無法正確識別的BUG。
if (tempName[0] == '/'')
{
if (tempName[tempName.Length - 1] == '/'')
{
tempName = tempName.Substring(1, tempName.Length - 2);
}
else
{
tempName = tempName.Substring(1, tempName.Length - 1);
}
}
if (!alTables.Contains(tempName))
{
alTables.Add(tempName);
}
}
odn.Close();
if (alTables.Count == 0)
{
return null;
}
return alTables;
}

代碼
代碼如下:
/// <summary>
/// 獲取指定路徑、指定工作簿名稱的Excel數(shù)據(jù)
/// </summary>
/// <param name="FilePath">文件存儲路徑</param>
/// <param name="WorkSheetName">工作簿名稱</param>
/// <returns>如果爭取找到了數(shù)據(jù)會返回一個完整的Table,否則返回異常</returns>
public DataTable GetExcelData(string FilePath, string WorkSheetName)
{
DataTable dtExcel = new DataTable();
OleDbConnection con = new OleDbConnection(GetExcelConnection(FilePath));
OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from [" + WorkSheetName + "$]", con);
//讀取
con.Open();
adapter.FillSchema(dtExcel, SchemaType.Mapped);
adapter.Fill(dtExcel);
con.Close();
dtExcel.TableName = WorkSheetName;
//返回
return dtExcel;
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 茂名市| 西昌市| 新源县| 江孜县| 黑河市| 称多县| 和林格尔县| 游戏| 申扎县| 澄城县| 武宁县| 衡南县| 澜沧| 纳雍县| 宿松县| 凌海市| 米泉市| 新和县| 巩留县| 尖扎县| 耿马| 通江县| 济阳县| 长治县| 龙里县| 平远县| 新昌县| 尉犁县| 门源| 子洲县| 白河县| 河津市| 濉溪县| 临清市| 兴安县| 会同县| 七台河市| 怀安县| 江口县| 安图县| 茶陵县|