1,先 引用第三方 导入控件:
<script src="../../ProductFlow/jquery-easyui-1.4.3/ajaxfileupload.js"></script>
2,在页面初始化加载时,声明该 导入的控件:
<input type="file" id="file1" name="file" style=" 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 数据