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];
    }

 

转载于:https://www.cnblogs.com/Yellowshorts/p/3598369.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值