c#读取excel的xls和xlsx文件的方法

时间:2022-10-05 11:44:03
.NET
读取Excel 2007的xlsx文件和读取老的.xls文件是一样的,都是用Oledb读取,仅仅连接字符串不同而已。
读取xlsx
用的是Microsoft.Ace.OleDb.12.0;
具体操作方法如下:public static DataTable GetExcelToDataTableBySheet(string FileFullPath,string SheetName){            //string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + FileFullPath + ";Extended Properties='Excel 8.0; HDR=NO; IMEX=1'"; //此连接只能操作Excel2007之前(.xls)文件            string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" +"data source=" + FileFullPath + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";//此连接可以操作.xls与.xlsx文件            OleDbConnection conn = new OleDbConnection(strConn);            conn.Open();            DataSet ds = new DataSet();            OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", SheetName), conn);                    //("select * from [Sheet1$]", conn);            odda.Fill(ds, SheetName);            conn.Close();            return ds.Tables[0]; }   老的xls就很简单,只是注意是Jet,还有ver是8.0
    ResultInfo<List<HighEndNetFinancialEntity>> Result = new ResultInfo<List<HighEndNetFinancialEntity>>();
string ver = "";
int pos = FilePath.LastIndexOf(".") + 1;
string postFileName = FilePath.Substring(pos, FilePath.Length - pos);
if (postFileName == "xls")
{
ver = "8.0";
}

else
{
Result.Message = "请上传Exel-xls文件。";
Result.IsSuccess = false;
return Result;
}

DataSet result = null;

string strConn = "Provider=Microsoft.<span style="color:#ff0000;">Jet</span>.OLEDB.4.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=\"Excel " + ver + ";IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
try
{
conn.Open();
string strExcel = "select * from [sheet1$]";
OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);
result = new DataSet();
myCommand.Fill(result, "MFMui");
}
catch (Exception e)
{
if (e != null)
{
Result.Message += e.Message;
return Result;
}
}
finally
{
conn.Close();
}