var ws;
$(
function () {
var url = "ws://" + window.location.hostname + ":" + window.location.port + "/api/WSChatSub";
// alert(url);
ws = new WebSocket(url);
ws.onopen = function () {
alert("链接成功");
//$("#messageSpan").text("Connected!");
};
ws.onmessage = function (result) {
console.log(result.data);
if (result.data != "")
{
var arr = result.data.split(',');
if (arr[1] == "true")
{
alert(arr[0]);
var name=arr[0].split('/');
window.location.href = "@Url.Content("~/Upload")/"+name[2];
// window.open(arr[1]);
}
else
$("#mes").text("正在导出第:" + arr[0] + "条数据!共" + arr[1] + "条数据");
}
// $('#progress').css({ width: (result.data * 0.05) + "%" });
// alert(result.data);
// $("#messageSpan").text(result.data);
};
ws.onerror = function (error) {
alert("链接错误");
// $("#messageSpan").text(error.data);
};
ws.onclose = function () {
// $("#messageSpan").text("Disconnected!");
};
}
);
//控制器
public class WSChatController : ApiController
{
// GET: WSChat
public HttpResponseMessage Get()
{
if (HttpContext.Current.IsWebSocketRequest)
{
HttpContext.Current.AcceptWebSocketRequest(ProcessWSChat);
}
return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
}
//List<T> GetList(Type obj)
//{
// DbEntities db = new DbEntities();
// return db.Set(obj)
//}
public virtual ArrayList data { get; set; }
public virtual Type type { get; set; }
private async Task ProcessWSChat(AspNetWebSocketContext arg)
{
WebSocket socket = arg.WebSocket;
while (true)
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
if (socket.State == WebSocketState.Open)
{
string message = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
string returnMessage = "You send :" + message + ". at" + DateTime.Now.ToLongTimeString();
//if (System.Web.HttpContext.Current.Session["Excel"] != null)
//{
// var a = System.Web.HttpContext.Current.Session["Excel"];
//}
//DbEntities db = new DbEntities();
var stu = data;// db.STU_BaseInfo.ToList();
// var dtSource = NPOIExcelHelper.ToDataTable<STU_BaseInfo>(db.STU_BaseInfo.ToList());
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
//记录当前导出条数
int index = 1;
// Type type = typeof(STU_BaseInfo);
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
System.Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? p.PropertyType.GenericTypeArguments[0] : p.PropertyType)); });
foreach (var item in stu)
{
if (index % 2 == 0)
{
//实时向前台写导出条数
string mes=string.Format("{0},{1}",(index/2),stu.Count);
buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(mes));
await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(p => row[p.Name] = p.GetValue(item) == null ? DBNull.Value : p.GetValue(item));
//加入到DataTable
dt.Rows.Add(row);
index++;
}
MemoryStream ms = new MemoryStream();
var address = "~/Upload/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
string Path = System.Web.HttpContext.Current.Server.MapPath(address);//文件保存地址
var path = System.Web.HttpContext.Current.Server.MapPath("~/Template/Student_Template.xls");
FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
HSSFWorkbook workbook = new HSSFWorkbook(file);
//HSSFSheet sheet = (HSSFSheet)workbook.GetSheet("Sheet1");
HSSFSheet sheet = (HSSFSheet)workbook.GetSheet("Sheet1");
HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
if (dt != null && dt.Rows.Count > 0)
{
for (int x = 0; x < dt.Rows.Count; x++)
{
if (index % 2 == 0)
{
string mes=string.Format("{0},{1}",(index/2),stu.Count);
//实时向前台写导出条数
buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(mes));
//buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes((index / 2).ToString()+","+));
await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
index++;
// System.Web.HttpContext.Current.Session["Excel"] = x.ToString();
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(x + 1);
for (int y = 0; y < dt.Columns.Count; y++)
{
HSSFCell newCell = (HSSFCell)dataRow.CreateCell(y);
string drValue = dt.Rows[x][y].ToString();
switch (dt.Columns[y].DataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
System.DateTime dateV;
System.DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV);
newCell.CellStyle = dateStyle;//格式化显示
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
}
}
}
}
sheet.ForceFormulaRecalculation = true;
using (ms)
{
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
//sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
}
// ms = NPOIExcelHelper.DataTableToExcel(stu, path, 1);//详见NPOI导出execl
using (FileStream fs = new FileStream(Path, FileMode.Create, FileAccess.Write))
{
byte[] res = ms.ToArray();
fs.Write(res, 0, res.Length);
fs.Flush();
}
string fileName = "学生信息.xls";//下载文档名
//导出成功向前台写下载地址
buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(address + ",true"));
await socket.SendAsync(buffer, WebSocketMessageType.Text,true, CancellationToken.None);
}
else
{
break;
}
}
}
}
//控制器
public class WSChatSubController : WSChatController
{
//数据源
public override ArrayList data
{
get
{
DbEntities db = new DbEntities();
return new ArrayList( db.STU_BaseInfo.ToList());
}
set
{
base.data = value;
}
}
//数据类型
public override Type type
{
get
{
return typeof(STU_BaseInfo);
}
set
{
base.type = value;
}
}
//public override List<object> GetData()
//{
// DbEntities db = new DbEntities();
// return db.STU_BaseInfo.Cast<object>().ToList();
//}
//public override System.Net.Http.HttpResponseMessage Get()
//{
// return base.Get();
//}
}