excel大量匯入資料庫

來源:互聯網
上載者:User

後台代碼: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.IO;

public partial class Excel : System.Web.UI.Page
{
  
    int count = 0;
    int counts = 0;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnExcel_Click(object sender, EventArgs e)
    {
        string filePath = "";
        //DirectoryInfo mydir = new DirectoryInfo(@"F:\Excel");
        DirectoryInfo mydir = new DirectoryInfo(Server.MapPath("file/"));
        FileInfo[] files = mydir.GetFiles();
        for (int i = 0; i < files.Length; i++)
        {
            //filePath = "F:\\Excel\\" + files[i].ToString();
            filePath = Server.MapPath("file/" + files[i].ToString());
            //string xlsName = files[i].ToString().Replace(".xls", "");
            string connString03 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=no;IMEX=1;'";//hdr=no或yes:是否輸入標題(如:姓名,性別,==) IMEX=1:表示是否強制轉換為文本
           // string connString07 = "Provider=Microsoft.Ace.OleDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;HDR=Yes;IMEX=1;'";
            OleDbConnection excelconn = new OleDbConnection(connString03);
            excelconn.Open();
            string excelsel = "select * from [Sheet1$]";
            OleDbCommand excelCmd = new OleDbCommand(excelsel,excelconn);
            OleDbDataAdapter excelda = new OleDbDataAdapter();
            excelda.SelectCommand = excelCmd;
            DataSet excelDs = new DataSet();

            excelda.Fill(excelDs);

            DataTable dt = excelDs.Tables[0];

            DataView myview = new DataView(dt);
            try
            {
                foreach (DataRowView myDrv in myview)
                //for (int j = 0; j < excelDs.Tables[0].Rows.Count;j++ )
                {
                    count++;
                    string pro_Excel = "excel_Insert";
                    SqlParameter[] param = {new SqlParameter("@Name",SqlDbType.NVarChar),
                                            new SqlParameter("@Info",SqlDbType.NVarChar),
                                            new SqlParameter("@address",SqlDbType.NVarChar)
                                           };
                    //param[0].Value = excelDs.Tables[0].Rows[j][0].ToString().Trim();
                    //param[1].Value = excelDs.Tables[0].Rows[j][1].ToString().Trim();
                    //param[2].Value = excelDs.Tables[0].Rows[j][2].ToString().Trim();
                    param[0].Value = myDrv[0].ToString().Trim();
                    param[1].Value = myDrv[1].ToString().Trim();
                    param[2].Value = myDrv[2].ToString().Trim();

                    counts = sqlHelper.ExecuteNonQuery(sqlHelper.conn, CommandType.StoredProcedure, pro_Excel, param);

                }
                if (counts > 0)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('匯入成功')</script>");
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('操作失敗')</script>");
                }
            }
            catch
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('第 "+ count.ToString() + "條資料出錯')</script>");
                excelconn.Close();
            }
            excelconn.Close();
        }
    }
}

//前台

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Excel.aspx.cs" Inherits="Excel" %>

<%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:WebUserControl ID="WebUserControl1" runat="server" /><asp:button ID="btnExcel" runat="server" Text="匯入Excel" onclick="btnExcel_Click" />
    </div>
    </form>
</body>
</html>

 

//預存程序

create proc excel_Insert 

@name nvarchar(50), 
@Info nvarchar(50), 
@address nvarchar(50) 

as 
insert into Excel(Name,Info,address) values(@name,@Info,@address) 

 

 

另附一句話匯入

insert into ProJHInfo_Bas select *  from OPENROWSET('MICROSOFT.ACE.OLEDB.12.0','Excel 5.0;HDR=YES;DATABASE=" +
url + "',sheet1$)

url為excel地址,註:此語句 資料表列與Excel列相同

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.