程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 上傳EXCEL並把內容批量寫入指定數據庫

上傳EXCEL並把內容批量寫入指定數據庫

編輯:.NET實例教程

注明:必須按照數據庫字段的“順序”,“字段格式 ”來寫EXCEL;自動編號不要寫入Excel。

我這裡用的是Access

前台代碼:



<%...@ Page language="c#" Codebehind="Excel.ASPx.cs" AutoEventWireup="false" Inherits="TestAll.Excel" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD Html 4.0 Transitional//EN" >
<Html>
    <HEAD>
        <title>Excel</title>
        <meta content="Microsoft Visual Studio .Net 7.1" name="GENERATOR">
        <meta content="C#" name="CODE_LANGUAGE">
        <meta content="JavaScript" name="vs_defaultClIEntScript">
        <meta content="http://schemas.microsoft.com/intellisense/IE5" name="vs_targetSchema">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <TABLE id="Table1"  height="100%"
                cellSpacing="1" cellPadding="1" width="100%" border="0">
                <TR>
                    <TD  align="center" colSpan="3"><FONT face="宋體">&nbsp;</FONT>
                        <TABLE id="Table3"  cellSpacing="1" cellPadding="1" width="300"
                            border="0">
                            <TR>
                                <TD  align="center" colSpan="2">Excel批量上傳</TD>
                            </TR>
                            <TR>
                                <TD align="right">表格名稱:</TD>
                                <TD><asp:textbox id="txtTableName" runat="server" Font-Size="12px"></ASP:textbox></TD>
                            </TR>
                            <TR>
                                <TD align="right">位置:</TD>
                                <TD><INPUT id="file"  type="file" runat="server"></TD>
                            </TR>
                            <TR>
                                <TD></TD>
                                <TD align="center"><asp:button id="Button1" runat="server" Text="上  傳" Border></ASP:button></TD>
                            </TR>
                            <TR>
                                <TD  align="right" colSpan="2">&gt;&gt;表名稱為Excel表格中左下角的字段名</TD>
                            </TR>
                        </TABLE>
                &
nbsp;   </TD>
                </TR>
            </TABLE>
        </form>
    </body>
</Html>

後台代碼:



using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using System.Configuration;

namespace  TestAll
...{
    /**//// <summary>
    /// Excel 的摘要說明。
    /// </summary>
    public class Excel : System.Web.UI.Page
    ...{protected System.Web.UI.WebControls.Button Button1;
        protected System.Web.UI.HtmlControls.HtmlInputFile File1;
        protected System.Web.UI.WebControls.TextBox txt_tbname;
        protected System.Web.UI.HtmlControls.HtmlInputFile file;
        protected System.Web.UI.WebControls.TextBox txtTableName;
        public string ST_ConnectionString;
        private void Page_Load(object sender, System.EventArgs e)
        ...{
            
        }

        Web 窗體設計器生成的代碼#region Web 窗體設計器生成的代碼
        override protected void OnInit(EventArgs e)
        ...{
            //
            // CODEGEN: 該調用是 ASP.Net Web 窗體設計器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }
    &nbsp;   
        /**//// <summary>
        /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
        /// 此方法的內容。
        /// </summary>
        private void InitializeComponent()
        ...{    
            this.Button1.Click += new System.EventHandler(this.Button1_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion
        private void Button1_Click(object sender, System.EventArgs e)
        ...{
            if (!file.Value.ToLower().EndsWith("xls"))
            ...{
                Response.Write("<script>alert(''只能導入Excel類型文件'');</script>");  return;
            }
            if (txtTableName.Text.Trim() == "")
            ...{
                Response.Write("<script>alert(''請填寫Excel表單名'');</script>");
                return;
            }
            //獲取上傳文件的路徑

            string myFile=file.PostedFile.FileName;
            string fileName=myFile.Substring(myFile.LastIndexOf("\")+1);
            file.PostedFile.SaveAs(Server.MapPath("../xls")+"\"+fileName);
            string tbname = txtTableName.Text.Trim();    //表名

            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+Server.MapPath("../xls")+"\"+fileName+";"+"Extended PropertIEs=''Excel 8.0;hdr=yes;imex=1'';";
            
            DataSet myDataSet = new DataSet();
            OleDbConnection conn = new OleDbConnection(strConn);
            OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM ["+tbname+"$]", strConn);
            try
        ...{
                myCommand.Fill(myDataSet);
            }
            catch(Exception ex)
            ...{
                string aa = ex.Message;
                Response.Write("<script>alert(''表單名不正確'');</script>");
                return;
            }
            
//            //復制
            ST_ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(ConfigurationSettings.APPSettings["ConnectionString1"]);
            OleDbConnection con=new OleDbConnection(ST_ConnectionString);
            OleDbDataAdapter da=new OleDbDataAdapter("select * from SW_Product order by id desc",con);
            DataSet ds1=new DataSet();
            da.Fill(ds1);//原有
            for(int i=0;i<myDataSet.Tables[0].Rows.Count;i++)
            ...{
                DataRow dr=ds1.Tables[0].NewRow();
                for (int j=0; j<ds1.Tables[0].Columns.Count;j++)

 ...{

                    dr[j]=myDataSet.Tables[0].Rows[i][j];
                }
                ds1.Tables[0].Rows.Add(dr);
            }
            try
            ...{
                OleDbCommandBuilder cb=new OleDbCommandBuilder(da);
                cb.QuotePrefix="[";
                cb.QuoteSuffix="]";
                da.Update(ds1);
                Response.Write("<script>alert(''添加成功!'');</script>");
            }
            catch(Exception ex1)
            ...{
                Response.Write("<script>alert(''"+ex1.Message.ToString()+"'');</script>");
            }
        }
    }
}


具體路徑自行左修改就OK了。

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved