Excel2007导入

//导入支持excel2007 及各类数据验收

        StringfileStyle = System.IO.Path.GetExtension(Fud_Execl.FileName);

        if(fileStyle.ToUpper() == ".XLS" ||fileStyle.ToUpper() == ".XLSX")

        {

            //设置上传到服务器的EXECL文档的文件名

            StringstrFileName = "电费已收" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileStyle;

            //设置上传到服务器的EXECL文档的路径

            StringstrPath = Server.MapPath("..\\..")+ "\\Excel\\InExcel\\" +strFileName;

            if(Fud_Execl.PostedFile.ContentLength != 0)

            {

                // 上传文件到服务器上

               Fud_Execl.PostedFile.SaveAs(strPath);

 

                //读取EXCEL文件到datatable中

                DataTable dtExcel = new DataTable();

 

                try

                {

                    string strExcel = "select* from [Sheet1$]";

                    string connStr = string.Format("Provider={2};Data Source ={0};Extended Properties='Excel {1};HDR=YES;IMEX=1'",

                        strPath,fileStyle.ToUpper() == ".XLS" ? "8.0" : "12.0",fileStyle.ToUpper() == ".XLS" ? "Microsoft.Jet.OLEDB.4.0" : "Microsoft.ACE.OLEDB.12.0");

                    using (OleDbConnection conn = new OleDbConnection(connStr))

                    {

                        conn.Open();

                       OleDbDataAdapter da;

                        string sql = "select* from [Sheet1$]  ";

                        da = new OleDbDataAdapter(sql, conn);

                        da.Fill(dtExcel);

                       da.Dispose();

                       conn.Close();

                       conn.Dispose();

                    }

                }

                catch (System.Exceptionex)

                {

                    GodTools.Show(this,"导入失败,读取工作表时出错,可能工作表不存在。请将工作表名改为Sheet1!");

                    return;

                }

 

                // 保存EXCEL数据到数据库中

                string strErr = "";//返回系统错误

                string strMsg = this.saveData(dtExcel,ref strErr);//返回自定义错误

                if (strMsg == "")

                {

                   ClientScript.RegisterStartupScript(this.GetType(),"st", "alert('上传与检测成功!');", true);

                }

                else

                {

                    ClientScript.RegisterStartupScript(this.GetType(), "st","alert('" + strMsg + strErr + "');", true);

                }

            }

        }

        else

        {

           ClientScript.RegisterStartupScript(this.GetType(),"st", "alert('只允许导入后缀名为XLS,XLSX的文件');", true);

        }


你可能感兴趣的:(Excel2007导入)