
1,先 引用第三方 導入控件:
<script src="../../ProductFlow/jquery-easyui-1.4.3/ajaxfileupload.js"></script>
2,在頁面初始化加載時,聲明該 導入的控件:
<input type="file" id="file1" name="file" style="width: 202px; height: 31px" />
<input type="button" value="上傳" />
$(function () {
$(":button").click(function () {
ajaxFileUpload();
});
});
//上傳控件
function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: "../Handler/ImportHandler.ashx", //用於文件上傳的服務器端請求地址
secureuri: false, //是否需要安全協議,一般設置為false
fileElementId: 'file1', //文件上傳域的ID
dataType: 'json', //返回值類型 一般設置為json
success: function (data, status) //服務器成功響應處理函數
{
if (data.status == "error") {
$.messager.alert("提示", data.msg);
return;
}
$("#container").show();
InitGrid(data);
$.messager.alert("提示", "文件已上傳,數據加載完畢!");
},
error: function (data, status, e)//服務器響應失敗處理函數
{
$.messager.alert("提示", "上傳失敗!");
}
}
)
return false;
}
2,讀取 從頁面上傳的Excel 里面的數據:
ImportHandler.ashx:
<%@ WebHandler Language="C#" Class="ImportHandler" %>
using System;
using System.Web;
using System.IO;
using NPOI.SS.UserModel;
using System.Data;
using System.Collections.Generic;
using System.Data.OleDb;
using OThinker.H3.Portal;
public class ImportHandler : OThinker.H3.Portal.HttpHandlerBase
{
/// <summary>
///校驗上傳文件格式(服務器響應處理函數)
/// </summary>
/// <param name="msg"></param>
/// <param name="status"></param>
/// <param name="newFileName"></param>
public void showMsg(string msg, string status, string newFileName)
{
string res = "";
res = "{ status:'" + status + "', msg:'" + msg + "',fileName:'" + newFileName + "'}";
this.Response.Write(res);
this.Response.End();
}
public override void DoAction(HttpContext context)
{
System.Web.HttpFileCollection files = this.Request.Files;
if (files == null || files.Count == 0) return;
string attachmentId = Guid.NewGuid().ToString();
DataTable data = new DataTable();
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i] as System.Web.HttpPostedFile;
if (file.ContentLength == 0) continue;
string fileName = file.FileName;
string extenstion = fileName.Substring(fileName.LastIndexOf(".") + 1);//后綴名
if (extenstion.Equals("xls") || extenstion.Equals("xlsx"))
{
string sheetName = "sheet1";
bool isFirstRowColumn = true;
IWorkbook workbook = null;
ISheet sheet = null;
int startRow = 0;
try
{
workbook = WorkbookFactory.Create(file.InputStream);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一個cell的編號 即總的列數
if (isFirstRowColumn)
{
for (int j = firstRow.FirstCellNum; j < cellCount; ++j)
{
DataColumn column = new DataColumn(firstRow.GetCell(j).StringCellValue);
data.Columns.Add(column);
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的標號
int rowCount = sheet.LastRowNum;
for (int j = startRow; j <= rowCount; ++j)
{
IRow row = sheet.GetRow(j);
if (row == null) continue; //沒有數據的行默認是null
DataRow dataRow = data.NewRow();
for (int k = row.FirstCellNum; k < cellCount; ++k)
{
if (row.GetCell(k) != null) //同理,沒有數據的單元格都默認是null
dataRow[k] = row.GetCell(k).ToString();
}
data.Rows.Add(dataRow);
}
}
}
catch
{
}
finally
{
// stream.Close();
}
}
else
{
string msg = "導入文件的格式不正確,請先下載模板!";
showMsg(msg, "error", null);
break;
}
}
string ResJsonStr = "{ \"rows\": ";
if (data.Rows.Count > 0)
{
data.Rows.RemoveAt(0);//刪除第一行
int rowCount = data.Rows.Count;
for (int i = 0; i < rowCount; i++)
{
string str = data.Rows[i][0].ToString();
//篩選出空行,和隱藏行
if (str == "index")
{
data.Rows.RemoveAt(i);
break;
}
}
Newtonsoft.Json.Converters.IsoDateTimeConverter timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd hh:mm";
ResJsonStr = ResJsonStr + Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented, timeConverter)
+ ", \"total\": " + data.Rows.Count + " }";
this.Response.Write(ResJsonStr.ToString());
this.Response.End();
}
else
{
string msg = "請先選擇正確的Excel文件,再上傳!";
showMsg(msg, "error", null);
}
}
}
3, ImportHandler的 父類: OThinker.H3.Portal.HttpHandlerBase
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;
namespace OThinker.H3.Portal
{
/// <summary>
/// H3 Portal 批處理程序基類,封裝了Engine,UserValidator,JavaScriptSerializer,Request,Response,Session
/// </summary>
public abstract class HttpHandlerBase : PortalPage, IHttpHandler, IRequiresSessionState
{
#region 上下文相關
protected HttpContext Context;
protected HttpRequest Request;
protected HttpResponse Response;
protected HttpSessionState Session;
#endregion
#region Js序列化對象
private JavaScriptSerializer _JsSerializer = null;
/// <summary>
/// 獲取JS序列化對象
/// </summary>
protected JavaScriptSerializer JSSerializer
{
get
{
if (_JsSerializer == null)
{
_JsSerializer = new JavaScriptSerializer();
}
return _JsSerializer;
}
}
#endregion
public void ProcessRequest(HttpContext context)
{
this.Context = context;
this.Request = context.Request;
this.Response = context.Response;
this.Session = context.Session;
if (this.UserValidator == null)
{
if (this.Request.Headers["x-requested-with"] != null && this.Request.Headers["x-requested-with"].Equals("XMLHttpRequest", StringComparison.InvariantCultureIgnoreCase))
{
this.Response.Write("PortalSessionOut");
this.Response.End();
}
}
else
{
this.DoAction(context);
}
}
/// <summary>
/// 事件執行
/// </summary>
public abstract void DoAction(HttpContext context);
public bool IsReusable
{
get
{
return false;
}
}
}
}
如何將 從Excel 中讀取出來的數據 顯示到 easyui的dataGrid中:
$('#datagrid').datagrid('loadData', data);//data 就是后台傳入的json 數據
