关闭

xls和xlsx的打开方式

1152人阅读 评论(0) 收藏 举报
分类:

AccessDatabaseEngine.exe自然是要装的,但是关键是Provider=Microsoft.Jet.Oledb.4.0一定要替换成Provider=Microsoft.ACE.OLEDB.12.0因为其中的Jet和ACE很相似但是却很容易忽略,这个是我的代码:

 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 if (postFileName == "xlsx")
            {
                ver = "12.0";
            }
            else
            {
                Result.Message = "请上传Exel-xls文件。";
                Result.IsSuccess = false;
                return Result;
            }

            DataSet result = null;
            //string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + FilePath + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
            //string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=\"Excel " + ver + ";IMEX=1\"";
             string strConn="";
            if (postFileName == "xls")
             strConn = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" + FilePath + "; Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1;\""; 
             else if (postFileName == "xlsx")
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + FilePath + "; Extended Properties=\"Excel 12.0; HDR=Yes; 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, "HighEndNetFinancial");
            }
            catch (Exception e)
            {
                if (e != null)
                {
                    Result.Message += e.Message;
                    return Result;
                }
            }
            finally
            {
                conn.Close();
            }


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:699556次
    • 积分:11150
    • 等级:
    • 排名:第1421名
    • 原创:352篇
    • 转载:438篇
    • 译文:2篇
    • 评论:49条
    最新评论