110,534
社区成员
发帖
与我相关
我的任务
分享
public static DataSet ExcelToDS (string file)
{
//string strConn = "Provider=Microsoft.Jet.OLEDB.12.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;HDR=NO;IMEX=1';";
string connstring = "";
string filetype = file.Substring(file.LastIndexOf('.') + 1);
DataSet dt = null;
if (filetype.ToLower() == "xlsx")
{
// Office 07及以上版本 不能出现多余的空格 而且分号注意
connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
}
else //if (filetype.ToLower() == "xls")
{
//Office 07以下版本
connstring = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
}
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
//string tableName = schemaTable.Rows[0][2].ToString().Trim();
string tableName = "sheet1$";
string strExcel = "";
OleDbDataAdapter myCommand = null;
strExcel = "select * from [" + tableName + "]";
myCommand = new OleDbDataAdapter(strExcel, connstring);
dt = new DataSet();
myCommand.Fill(dt, "table1");
conn.Close();
return dt;
}
}