c# + extjs 上传excel文件并保存到数据库

页面代码:

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





    导入用户
    


    
    
 
  


   
    


extjs代码:

Ext.onReady(function(){   
    var form = new Ext.form.FormPanel({
        renderTo: 'file',
        labelAlign: 'right',
        title: '文件上传',
        labelWidth: 60,
        frame: true,
        //url: 'UploadFile.aspx',//fileUploadServlet   
        width: 300,
        height: 200,
        fileUpload: true,
        items: [{
            xtype: 'textfield',
            fieldLabel: '文件名1',
            name: 'file',
            inputType: 'file'//文件类型
        }],

        buttons: [{
            text: '上传',
            handler: function () {
                form.getForm().submit({
                    waitTitle: '系统提示',
                    waitMsg: '正在上传,请等待...',
                    url: 'UploadFile.aspx',
                    method: 'POST',
                    success: function (form, action) {
                        Ext.Msg.alert('恭喜', '用户信息导入成功!');
                    },
                    failure: function () {
                        Ext.Msg.alert('错误', '用户信息导入失败!');
                    }
                });
            }
        }]
    });   
                                    
}); 


 

后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
//using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

using System.Data.OleDb;
using System.Text;


public partial class UploadFile : System.Web.UI.Page
{
    public string jSONString = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        
        try
        {   //文件存储路径
            string saveFoler = Server.MapPath("upload_files/");
            string savePath, fileName;
            //遍历File表单元素 ,可以上传数个文件
            for (int iFile = 0; iFile < Request.Files.Count; iFile++)
            {
                HttpPostedFile postedFile = Request.Files[iFile];
                fileName = Path.GetFileName(postedFile.FileName);
                if (fileName != "")
                {
                    string fileType = fileName.Substring(fileName.LastIndexOf("."));
                    //唯一编号
                    string newName = Guid.NewGuid().ToString("N") + fileType;
                    savePath = saveFoler + newName;
                    //检查是否在服务器上已经存在用户上传的同名文件
                    if (File.Exists(savePath))
                    {
                        File.Delete(savePath);
                    }
                    postedFile.SaveAs(savePath);
                    //保存到数据库中
                    ExcelToDS(savePath);
                }
            }
            jSONString = "{success:true,message:'上传完成!'}";
        }
        catch(Exception ex)
        {
            jSONString = "{success:false,message:'上传失败,可能因为上传文件过大导致!'}";
        }

        Response.Write(jSONString);
        Response.Flush();
    }

    //导入到数据库
    public void ExcelToDS(string path)         {              

          string filePath = path; 

          string connExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=YES\""; 
         
          try 
          { 
         
            OleDbConnection oleDbConnection = new OleDbConnection(connExcel); 

            oleDbConnection.Open();

	   //方法1
           // string olestr = "select * from [Sheet1$]";
           //   OleDbCommand oleComm = new OleDbCommand(olestr, oleDbConnection);
           //   oleComm.Connection = oleDbConnection;
           // OleDbDataAdapter oleDa = new OleDbDataAdapter();
           // oleDa.SelectCommand = oleComm;
           // DataSet ds = new DataSet();
           // oleDa.Fill(ds);

           // foreach (DataRow row in ds.Tables[0].Rows)
           // {
           //     string userInfo = row[0].ToString().Trim();
           // } 

            //获取excel表
         
            DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 
         

           //获取sheet名,其中[0][1]...[N]: 按名称排列的表单元素
         
           string tableName = dataTable.Rows[0][2].ToString().Trim(); 
         
           tableName = "[" + tableName.Replace("'","") + "]"; 
         
          
         
          //利用SQL语句从Excel文件里获取数据

           string query = "SELECT 用户编号,用户姓名,备注 FROM " + tableName; 
         
            
            DataSet dataSet = new DataSet(); 
         
         
            OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query,connExcel); 
         
            oleAdapter.Fill(dataSet,"UserInfo");

            //从excel文件获得数据后,插入记录到SQL Server的数据表
         
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection("Data Source=192.168.2.15;User ID=sa;Password=1231;Persist Security Info=True;Initial Catalog=HS");

            DataTable dataTable1 = new DataTable();

            System.Data.SqlClient.SqlDataAdapter sqlDA1 = new System.Data.SqlClient.SqlDataAdapter(@"SELECT RoleId, PassWord, UserState, DefaultPlace,UserId, UserName, Remarks FROM UserInfo", conn);


            System.Data.SqlClient.SqlCommandBuilder sqlCB1 = new System.Data.SqlClient.SqlCommandBuilder(sqlDA1); 
         
         
            sqlDA1.Fill(dataTable1); 
         
            foreach(DataRow dataRow in dataSet.Tables["UserInfo"].Rows) 
         
            { 
         
         
                DataRow dataRow1 = dataTable1.NewRow(); 
         
                dataRow1["UserId"] = dataRow["用户编号"]; 
         
                dataRow1["UserName"] = dataRow["用户姓名"]; 
         
                dataRow1["Remarks"] = dataRow["备注"];

                dataRow1["RoleId"] = 11;
                //默认密码为123
                dataRow1["PassWord"] = "123";
                dataRow1["DefaultPlace"] = 1;
                dataRow1["UserState"] = true; 

               dataTable1.Rows.Add(dataRow1); 
         
         } 
         
         
         
            sqlDA1.Update(dataTable1); 
         
            oleDbConnection.Close(); 
         
          } 
         
          catch(Exception ex) 
         
          { 
            Console.WriteLine(ex.ToString());
          } 
    }     
}


 

你可能感兴趣的:(js,c#,c#,文件上传,技术人)