zoukankan      html  css  js  c++  java
  • Excel导入到DataTable

    1.前台代码

    <asp:FileUpload ID="fupFiles" runat="server" />
    <asp:Button ID="btnImprot" runat="server" Text="导入" OnClick="btnImprot_Click" />

    2.后台代码

      protected void btnImprot_Click(object sender, EventArgs e)
        {
            String fileName = System.IO.Path.GetFileName(fupFiles.FileName);
            String path = Server.MapPath("~/" + fileName);
            fupFiles.SaveAs(path);
    
            DataTable dt = ImportExcelByDB(path);
           
        }
        public static DataTable ImportExcelByDB(string physicalPath)
        {
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + physicalPath + ";Extended Properties='Excel 8.0;HDR=yes'";
            //  Excel 2007
            if (physicalPath.ToLower().IndexOf(".xlsx") > 0 && physicalPath.ToLower().EndsWith("xlsx"))
            {
                //strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + physicalPath + "';Extended Properties='Excel 12.0;HDR=YES'";
                //strConn = "'Microsoft.ACE.OLEDB.12.0','Data Source=" + physicalPath + ";Extended Properties="Excel 12.0;HDR=Yes;IMEX=1"'";
                strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + physicalPath + ";Extended Properties='Excel 8.0;HDR=yes'";
            }
            //  Excel 2003
            if (physicalPath.ToLower().IndexOf(".xls") > 0 && physicalPath.ToLower().EndsWith("xls"))
            {
                //strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + physicalPath + "';Extended Properties='Excel 8.0;HDR=YES;'";
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + physicalPath + "';Extended Properties=Excel 8.0";
            }
            DataSet dst = new DataSet();
            OleDbConnection conn = new OleDbConnection(strConn);
            try
            {
                if (conn.State.ToString() == "Closed")
                {
                    conn.Open();
                }
                dst.Clear();
                string strSql = "SELECT * FROM  [Sheet1$]";
                OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, conn);
                adapter.Fill(dst, "[Sheet1$]");
                conn.Close();
            }
            catch (Exception ee)
            {
                return null;
            }
            return dst.Tables[0];
        }
  • 相关阅读:
    SVN配置文件详解
    让Linux开机运行命令
    find命令用法介绍
    关于js优化和css优化
    弹性盒布局、头尾固定中间部分自适应布局
    css样式重置(初始化)收集
    动态嵌套form,使用Stimulus Js库(前后端不分离)
    给Mac的Dictionary添加其他原装词典
    使用rvm关联ruby版本和rails版本。
    Rails6.0 Beta版本1: ActionText的简单使用
  • 原文地址:https://www.cnblogs.com/Yellowshorts/p/3598369.html
Copyright © 2011-2022 走看看