01
02
03
|
StreamReader sr = new StreamReader( "文件名以及完整路径" ,System.Text.Encoding.Default); string data = sr.ReadToEnd(); sr.Close(); |
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
|
/**/ /// <summary> /// 返回Excel数据源 /// </summary> /// <param name="filename">文件路径</param> /// <param name="TSql">TSql</param> /// <returns>DataSet</returns> public static DataSet ExcelToDataSet( string filename, string TSql) { DataSet ds; string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + filename; OleDbConnection myConn = new OleDbConnection(strCon); string strCom = TSql; myConn.Open(); OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn); ds = new DataSet(); myCommand.Fill(ds); myConn.Close(); return ds; } |
01
02
03
04
|
//设置T_Sql string TSql = "SELECT * FROM [sheel1$]" ; //读取数据 DataTable table = ExcelToDataSet(fullPath, TSql).Tables[0]; |
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
|
/// <summary> /// 动态取Excel表名 /// </summary> /// <param name="fullPath">文件路径</param> /// <returns></returns> public static string GetExcelFirstTableName( string fullPath) { string tableName = null ; if (File.Exists(fullPath)) { using (OleDbConnection conn = new OleDbConnection( "Provider=Microsoft.Jet." + "OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + fullPath)) { conn.Open(); tableName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null ).Rows[0][2].ToString().Trim(); } } return tableName; } |
01
02
03
04
05
|
string tableName = GetExcelFirstTableName( "文件 路径" ); //设置T_Sql string TSql = "SELECT * FROM [" + tableName + "]" ; //读取数据 DataTable table = ExcelToDataSet(fullPath, TSql).Tables[0]; |