程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> Excel、記事本數據導入到數據庫的實現方法

Excel、記事本數據導入到數據庫的實現方法

編輯:ASP.NET基礎

文件示例:
Excel:

記事本:

前台代碼:
復制代碼 代碼如下:
<div class="tab-content detail" id="divSecond" runat="server" visible="false">
            <fieldset >
             <p>
                <label>
                  選擇文件</label>
                  <asp:FileUpload ID="FileUpload1" runat="server"  /><asp:RequiredFieldValidator
                      ID="RequiredFieldValidator1" runat="server" ErrorMessage="請選擇要提交的Excel文件" ControlToValidate="FileUpload1"></asp:RequiredFieldValidator>
              </p>
              <p>
              <label>文件示例</label><img src="../images/ex_excel.jpg" />
              </p>
            </fieldset>
            <div class="clear"></div>
           <div class="clear"></div>
            <div style="margin-left:200px">
                <asp:Button ID="btnExcel" runat="server" Text="提 交" CssClass="button" 
                    onclick="btnExcel_Click"  />
                     
                <input class="button" type="button" value="返 回" onclick="javascript:window.location.href='CartList.aspx'" />
            </div>
          </div>
          <div class="tab-content detail" id="divThird" runat="server" visible="false">
            <fieldset >
              <p>
                <label>
                  選擇文件</label>
                  <asp:FileUpload ID="FileUpload2" runat="server" /> <asp:RequiredFieldValidator
                      ID="RequiredFieldValidator2" runat="server" ErrorMessage="請選擇要提交的tTXT文件"
                      ControlToValidate="FileUpload2"></asp:RequiredFieldValidator>
              </p>
              <p>
              <label>文件示例</label><img src="../images/ex_txt.jpg" />
              </p>
            </fieldset>
            <div class="clear"></div>
           <div class="clear"></div>
            <div style="margin-left:200px">
                <asp:Button ID="btnNotepad" runat="server" Text="提 交" CssClass="button"
                    onclick="btnNotepad_Click"  />
                     
                <input class="button" type="button" value="返 回" onclick="javascript:window.location.href='CartList.aspx'" />
            </div>
          </div>

後台代碼
復制代碼 代碼如下:
//Excel上傳
        protected void btnExcel_Click(object sender, EventArgs e)
        {         
              string backStr= UploadFile(FileUpload1, "Excel",1);
              if (backStr == "-1")
              {
                   //這裡是放返回消息的,改為對應放消息的方式就行了,Js這個類就不上傳了
                  Js.ShowSureMsgBox(this.Page,"請選擇要提交的Excel文件");
                  return;
              }
              else if (backStr == "-2")
              {
                  Js.ShowSureMsgBox(this.Page, "請選擇.xls或.xlsx類型文件");
                  return;
              }
              else
              {
                  string url = backStr;   //絕對路徑
                  DataTable dt = ExcelToDataSet(url);
                  if (dt.Rows.Count > 0)
                  {
                     for (int i = 0; i < dt.Rows.Count; i++)
                     {
                          //讀取每行數據         
                           string phoneNum= dt.Rows[i][0].ToString();            
                     }           
                  }
                  else
                  {
                      Js.ShowSureMsgBox(this.Page, "文件內容為空");
                  }
                  File.Delete(url);  //刪除上傳的文件
              }
        }
        //記事本上傳
        protected void btnNotepad_Click(object sender, EventArgs e)
        {
            string backStr = UploadFile(FileUpload2, "TXT",2);
            if (backStr == "-1")
            {
                Js.ShowSureMsgBox(this.Page, "請選擇要提交的TXT文件");
                return;
            }
            else if (backStr == "-2")
            {
                Js.ShowSureMsgBox(this.Page, "請選擇.txt類型文件");
                return;
            }
            else
            {
                string url = backStr;   //絕對路徑
                DataTable dt = ReadTXT(url);
                if (dt.Rows.Count > 0)
                {
                     for (int i = 0; i < dt.Rows.Count; i++)
                     {
                          //讀取每行數據         
                           string phoneNum= dt.Rows[i][0].ToString();            
                     }                
                }
                else
                {
                    Js.ShowSureMsgBox(this.Page, "文件內容為空");
                }
                File.Delete(url);  //刪除上傳的文件
            }
        }

        //上傳文件
        public string UploadFile(FileUpload FileUploadName, string varfilename,int type)
        {
                if (FileUploadName.HasFile)//判斷是否有上傳文件
                {
                    string fileExtension = System.IO.Path.GetExtension(FileUploadName.FileName).ToLower();//獲取文件的後綴名
                    if (type == 1)
                    {
                        if (fileExtension != ".xls" && fileExtension != ".xlsx")
                        {
                            return "-2";
                        }
                    }
                    if (type == 2)
                    {
                        if (fileExtension != ".txt")
                        {
                            return "-2";
                        }
                    }                 
                    string fpath = System.Web.HttpContext.Current.Server.MapPath("/Manager/Uploadfiles/" + varfilename + "/");//圖片存儲文件夾路徑,需要按照不同的需要進行相應的修改
                    if (!Directory.Exists(fpath))//查看存儲路徑的文件是否存在
                    {
                        Directory.CreateDirectory(fpath);   //創建文件夾,並上傳文件
                    }
                    string time = DateTime.Now.ToString("yyyyMMddhhmmssfff");//使用時間定義上傳圖片的名字
                    string picturename = time + fileExtension;
                    string newFilePath = fpath + picturename; //文件保存路徑
                    FileUploadName.SaveAs(newFilePath);
                    return newFilePath;   //絕對路徑

                }
                else
                {
                    return "-1";   //沒有文件
                }           
        }
        //讀取Excel數據
         public DataTable ExcelToDataSet(string filename)
        {
            string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + filename + ";Extended Properties=Excel 8.0";
            OleDbConnection conn = new OleDbConnection(strCon);
            conn.Open();
            //返回Excel的架構,包括各個sheet表的名稱,類型,創建時間和修改時間等 
            DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
            //包含excel中表名的字符串數組
            string[] strTableNames = new string[dtSheetName.Rows.Count];
            for (int k = 0; k < dtSheetName.Rows.Count; k++)
            {
                strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
            }
            OleDbDataAdapter myCommand = null;
            DataTable dt = new DataTable();
            //從指定的表明查詢數據,可先把所有表明列出來供用戶選擇
            string strExcel = "select * from [" + strTableNames[0] + "]";
            myCommand = new OleDbDataAdapter(strExcel, strCon);
            myCommand.Fill(dt);
            conn.Close();

            return dt;
        }
        //讀取記事本數據
         public DataTable ReadTXT(string dirTXT)
         {
             StreamReader objReader = new StreamReader(dirTXT);
             System.Data.DataTable dt = new System.Data.DataTable();
             dt.Columns.Add("DN", System.Type.GetType("System.String"));
             string sLine = "";
             while (sLine != null)
             {
                 sLine = objReader.ReadLine();
                 if (sLine != null && !sLine.Equals(""))
                 {
                     DataRow dr = dt.NewRow();
                     dr[0] = sLine;
                     dt.Rows.Add(dr);
                 }
             }
             objReader.Close();
             return dt;
         }

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