您的位置:首页 > 其它

从Excel、CSV文件获取数据

2017-10-17 16:54 295 查看
#region 从Excel获取数据
/// <summary>
/// 从Excel获取数据
/// </summary>
/// <param name="Path">文件路径(完整路径)</param>
/// <returns></returns>
public static DataSet ReadExcelToDS(string Path)
{
DataSet ds = new DataSet();
OleDbConnection conn = null;
OleDbDataAdapter da = null;
try
{
//string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";//此连接只能操作Excel2007之前(.xls)文件
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; //此连接可以操作.xls与.xlsx文件 (支持Excel2003 和 Excel2007 的连接字符串)
//备注: "HDR=yes;"是说Excel文件的第一行是列名而不是数据,"HDR=No;"正好与前面的相反。
//      "IMEX=1 "如果列中的数据类型不一致,使用"IMEX=1"可必免数据类型冲突。
conn = new OleDbConnection(strConn);
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
if (schemaTable != null)
{
string sheetName = schemaTable.Rows[0]["table_name"].ToString().Trim();
if (sheetName != null && sheetName.Length > 0)
{
string strExcel = "select * from [" + sheetName + "]";
da = new OleDbDataAdapter(strExcel, conn);
da.Fill(ds);
}
}
}
catch (Exception e)
{
throw e;
}
finally
{
if (conn != null) conn.Close();
if (da != null) da.Dispose();
}
return ds;
}
#endregion


#region 从CSV文件获取数据
/// <summary>
/// 从CSV文件获取数据
/// </summary>
/// <param name="Path">文件路径(完整路径)</param>
/// <returns></returns>
public static DataSet GetDataSetFromCSV(string Path)
{
string filePath = System.IO.Path.GetDirectoryName(Path);
string fileName = System.IO.Path.GetFileName(Path);
string strConn = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + filePath + ";Extensions=asc,csv,tab,txt;";
DataSet ds = new DataSet();
OdbcConnection Conn = new OdbcConnection(strConn);
OdbcDataAdapter da = null;
try
{
Conn.Open();
DataTable schemaTable = Conn.GetSchema("Tables", null);
if (schemaTable != null)
{
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
string sheetName = schemaTable.Rows[i]["table_name"].ToString().Trim();
if (fileName == sheetName)
{
string strSql = "select * from " + sheetName;
da = new OdbcDataAdapter(strSql, Conn);
da.Fill(ds);
break;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
Conn.Close();
if (da != null) da.Dispose();
}
return ds;
}
#endregion
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: