頁面代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>
<!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>
<link href="extjs3.3/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
<!--Extjs-->
<script src="extjs3.3/ext-base.js" type="text/javascript"></script>
<script src="extjs3.3/ext-all.js" type="text/javascript"></script>
<script type="text/javascript" src="upload.js"></script>
</head>
<body>
<div id="file"></div>
</body>
</html>
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());
}
}
}