C#读取Excel文件内容(WPS)

本地安装的WPS版本为 一、下载accessdatabaseengine_X64后安装 网址:https://www.microsoft.com/en-us/download/details.aspx?id=54920 二、项目中引用OleDb包 三、代码部分

//excelFilePath为文件路径(例如D:Test.xslx)
>   //string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
> excelFilePath + ";Extended Properties=Excel 8.0;HDR=YES;IMEX=1;";
>             string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + ";Extended Properties=Excel
> 12.0;HDR=Yes;IMEX=1;";
>             OleDbConnection conn = new OleDbConnection(strConn);
>             conn.Open();
>             var tables = 
> conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,
> null);
>                 var sheet = tables.Rows[0]["Table_Name"].ToString();
>                 var cmd = conn.CreateCommand();
>                 var strSQL = string.Format("select * from [{0}]", sheet);
>                 cmd.CommandText = strSQL;
>                 var reader = cmd.ExecuteReader();
>                 while (reader.Read())
>                 {
>                     var shotANDDevice = new ShotANDDevice
>                     {
>                         //按照列名取值
>                         ShotNo = reader["Test1"].ToString().Trim(),
>                         ShotName = reader["Test2"].ToString().Trim(),
>                         DeviceNo = reader["Test3"].ToString().Trim(),
>                         DeviceName = reader["Test4"].ToString().Trim()
>                         //按照列数取值(例如取第一、二、三、四列,结果同上)
>                          ShotNo = reader[0].ToString().Trim(),
>                         ShotName = reader[1].ToString().Trim(),
>                         DeviceNo = reader[2].ToString().Trim(),
>                         DeviceName = reader[3].ToString().Trim()
>                     };
>                 }
>                 conn.Close();
经验分享 程序员 微信小程序 职场和发展