protected static object DateYMD(string fieldXClass, object value) { if (value is DateTime && fieldXClass != "Ext.field.DatePicker") { return(YZStringHelper.DateToString((DateTime)value)); } return(value); }
public static DateTime StringToDate(string date, string time) { if (String.IsNullOrEmpty(time)) { time = "00:00"; } DateTime rv = YZStringHelper.StringToDate(date); rv = DateTime.Parse(YZStringHelper.DateToString(rv) + " " + time, YZStringHelper.datetimeCultureInfo); return(rv); }
public static string DateToString(DateTime date) { return(YZStringHelper.DateToString(date, null)); }
public virtual void ExportGrid2Excel(HttpContext context) { YZRequest request = new YZRequest(context); bool dynamicParams = request.GetBool("dynamicParams", false); //获得数据 - jsonResponse string jsonResponse; JObject jRequest = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(context.Request.Params["request"]))); string url = (string)jRequest["url"]; url = "~/" + url; JToken jToken; using (StringWriter sw = new StringWriter()) { HtmlTextWriter writer = new HtmlTextWriter(sw); HttpResponse response = new HttpResponse(writer); List <string> queryParams = new List <string>(); queryParams.Add("DateFormat=text"); foreach (KeyValuePair <string, JToken> property in (jRequest["params"] as JObject)) { queryParams.Add(property.Key + "=" + HttpUtility.UrlEncode((string)property.Value, Encoding.Default)); } HttpRequest callrequest = new HttpRequest(null, context.Request.Url.ToString(), String.Join("&", queryParams.ToArray())); HttpContext callcontext = new HttpContext(callrequest, response); IHttpHandler handler = PageParser.GetCompiledPageInstance(url, context.Server.MapPath(url), context); handler.ProcessRequest(callcontext); jsonResponse = sw.ToString(); jToken = JToken.Parse(jsonResponse); if (jToken is JObject) { JObject jObject = jToken as JObject; if (jObject["success"] != null && jObject["success"].Type == JTokenType.Boolean && (bool)jObject["success"] == false) { throw new Exception((string)jObject["errorMessage"]); } } } //将数据转化为Table DataTable table; string rootProperty = request.GetString("rootProperty", null); JArray jTable; if (String.IsNullOrEmpty(rootProperty)) { jTable = jToken as JArray; } else { jTable = (jToken as JObject)[rootProperty] as JArray; } foreach (JObject jRow in jTable) { foreach (KeyValuePair <string, JToken> jProperty in jRow) { if (jProperty.Value is JArray) { jRow[jProperty.Key] = Convert.ToString(jProperty.Value); } if (jProperty.Value is JObject) { jRow[jProperty.Key] = Convert.ToString(jProperty.Value); } } } table = jTable.ToObject <DataTable>(); table.TableName = "GridStore"; //SQL Server数据库中monery4位小数点处理 foreach (DataRow row in table.Rows) { foreach (DataColumn column in table.Columns) { object value = row[column]; if (value is decimal) { value = (decimal)Decimal.ToDouble((decimal)value); } row[column] = value; } } //生成Excel string templateExcel = request.GetString("templateExcel", String.Empty); HSSFWorkbook book = null; if (String.IsNullOrEmpty(templateExcel)) { book = this.NoTemplateExport(context, table); } else { if (!templateExcel.StartsWith("~/")) { templateExcel = "~/" + templateExcel; } Dictionary <string, string> reportParams = new Dictionary <string, string>(); //获得查询参数 foreach (KeyValuePair <string, JToken> property in (jRequest["params"] as JObject)) { reportParams.Add(property.Key, (string)property.Value); } if (!reportParams.ContainsKey("Kwd")) { reportParams.Add("Kwd", ""); } if (dynamicParams) { string strRuntimeParams = reportParams["params"]; if (!String.IsNullOrEmpty(strRuntimeParams)) { YZClientParamCollection runtimeParams = JArray.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(strRuntimeParams))).ToObject <YZClientParamCollection>(); foreach (YZClientParam clientParams in runtimeParams) { reportParams[clientParams.name] = Convert.ToString(clientParams.value); } } } //打开文件 using (FileStream file = new FileStream(context.Server.MapPath(templateExcel), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { book = new HSSFWorkbook(file); } DataSet dataset = new DataSet(); dataset.Tables.Add(table); YZExcelGenerate.Fill(book, reportParams, dataset); YZExcelGenerate.PrepareForOutput(book); } //Excel文件保存到流 byte[] bytes; using (MemoryStream ms = new MemoryStream()) { book.Write(ms); bytes = ms.ToArray(); } //导出文件名 string fileName = context.Request.Params["fileName"]; if (String.IsNullOrEmpty(fileName)) { fileName = "Export"; } fileName += YZStringHelper.DateToString(DateTime.Now) + ".xls"; this.ProcessResponseHeader(context, fileName, true); context.Response.BinaryWrite(bytes); //this.OnExported(context, table); //设置Response头 //context.Response.Clear(); //context.Response.ContentType = "application/vnd.ms-excel"; //context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); //context.Response.AppendHeader("Content-Length", bytes.Length.ToString()); //context.Response.BinaryWrite(bytes); //context.Response.End(); }
public void ProcessRequest(HttpContext context) { try { YZAuthHelper.OAuth(); //YZAuthHelper.AshxAuthCheck(); string method = context.Request.Params["Method"]; JsonItem JosonRv = new JsonItem(); if (YZStringHelper.EquName(method, "GET")) { string uid = YZAuthHelper.LoginUserAccount; using (BPMConnection cn = new BPMConnection()) { JsonItem data = new JsonItem(); JosonRv.Attributes.Add("data", data); cn.WebOpen(); UserAccount currentUser = cn.getCurrentUser(uid); User user = User.FromAccount(cn, uid); #region 用户信息 data.Attributes["Account"] = user.Account; data.Attributes["HRID"] = user.HRID; data.Attributes["DisplayName"] = user.ShortName; data.Attributes["Mobile"] = user.Mobile; data.Attributes["OfficePhone"] = user.OfficePhone; data.Attributes["HomePhone"] = user.HomePhone; data.Attributes["EMail"] = user.EMail; data.Attributes["Office"] = user.Office; data.Attributes["Birthday"] = YZStringHelper.DateToString(user.Birthday); data.Attributes["DateHired"] = YZStringHelper.DateToString(user.DateHired); data.Attributes["Desc"] = user.Description; #endregion #region 获得OU //获得OU String OULevel = String.Empty; String OUName = String.Empty; String Dept = String.Empty; BPMObjectNameCollection depts = new BPMObjectNameCollection(); MemberCollection members = OrgSvr.GetUserPositions(cn, uid); foreach (Member member in members) { OU ou = member.GetParentOU(cn); OULevel = ou.OULevel; Dept = ou.Name; String FullName = member.GetParentOU(cn).FullName; String mFullName = member.FullName; String mDepartment = member.Department; if (!ou.IsRootOU) { OUName = mFullName.Split(new char[2] { '/', '/' })[2]; depts.Add(OUName); } else { OUName = ou.Name; } if (String.IsNullOrEmpty(member.LeaderTitle)) { depts.Add(ou.Name); } else { depts.Add(String.Format("{0}({1})", ou.Name, member.LeaderTitle)); } } data.Attributes["Dept"] = String.Join(" > ", depts.ToArray()); #endregion UserCommonInfo userCommonInfo = UserCommonInfo.FromAccount(cn, uid); data.Attributes["AppSN"] = Net.Common.JosonRandom.GetRandomByDateTime(1, 999).Replace("/", ""); data.Attributes["AppCompany"] = OUName.GetShortName(); data.Attributes["AppDept"] = Dept; data.Attributes["AppDate"] = DateTime.Now; data.Attributes["AppHRName"] = user.ShortName; data.Attributes["AppHRID"] = YZAuthHelper.LoginUserAccount; data.Attributes["isSkyWorth"] = currentUser.AppFristDept != "制造中心" ? 0 : 1; data.Attributes["AppComDept"] = currentUser.AppCompany.ToConnects("\\") + currentUser.AppDept; JosonRv.Attributes.Add("success", true); JosonRv.Attributes.Add("successMessage", "ok"); context.Response.Write(JosonRv.ToString()); } } else if (YZStringHelper.EquName(method, "Submit")) { //遍历File表单元素 //HttpFileCollection files = HttpContext.Current.Request.Files; //try //{ // for (int iFile = 0; iFile < files.Count; iFile++) // { // ///检查文件扩展名字 // HttpPostedFile postedFile = files[iFile]; // string fileName, fileExtension; // fileName = System.IO.Path.GetFileName(postedFile.FileName); // if (fileName != "") // { // ///注意:可能要修改你的文件夹的匿名写入权限。 // postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("YZSoft/attachment/") + fileName); // } // } // HttpContext.Current.Response.Write("{success:true,msg:'File was successfully uploaded.'}"); //} //catch (System.Exception Ex) //{ // HttpContext.Current.Response.Write("{success:true,msg:'File was successfully uploaded.'}"); //} #region 接收数据 string uid = YZAuthHelper.LoginUserAccount; string EmpID = Convert.ToString(context.Request.Params["AppHRID"]); string EmpName = Convert.ToString(context.Request.Params["AppHRName"]); string LeaveID = Convert.ToString(context.Request.Params["LeaveID"]); string LeaveName = Convert.ToString(context.Request.Params["LeaveName"]); string LeaveTypeID = Convert.ToString(context.Request.Params["LeaveTypeID"]); String AppSN = Convert.ToString(context.Request.Params["AppSN"]); String AppCompany = Convert.ToString(context.Request.Params["AppCompany"]); String AppDept = Convert.ToString(context.Request.Params["AppDept"]); DateTime AppDate = Convert.ToDateTime(context.Request.Params["AppDate"]); String AppHRName = Convert.ToString(context.Request.Params["AppHRName"]); String AppHRID = Convert.ToString(context.Request.Params["AppHRID"]); String Address = Convert.ToString(context.Request.Params["Address"]); DateTime FromDate = YZStringHelper.StringToDate(context.Request.Params["startTime"]); DateTime ToDate = YZStringHelper.StringToDate(context.Request.Params["endTime"]); String allHours = Convert.ToString(context.Request.Params["allHours"]); int DayInt = Convert.ToInt32(allHours.Split('天')[0]); int HourInt = Convert.ToInt32(allHours.Split('天')[1].Split('小')[0]); String reasonWhyNote = Convert.ToString(context.Request.Params["reasonWhy"]); String suggestionMsg = Convert.ToString(context.Request.Params["suggestionMsg"]); String strAttachment = Convert.ToString(context.Request.Params["strAttachment"]); int isSkyWorth = Convert.ToInt32(context.Request.Params["isSkyWorth"]); #region iPHone 早期版本 客户端Bug修改 String strFromClient = submitFrom.UserAgent(context); //if (suggestionMsg.IndexOf("iphone") > -1 || suggestionMsg.IndexOf("iPhone") > -1) //{ // if (LeaveTypeID == "20") // { // LeaveTypeID = "30"; // } // else // { // LeaveTypeID = LeaveTypeID == "30" ? "20" : LeaveTypeID; // } //} #endregion #endregion using (BPMConnection cn = new BPMConnection()) { cn.WebOpen(); // Net.Common.GetRequestForm.Post<T> // http://extjs.org.cn/node/712 #region 提交数据 MemoryStream xmlStream = GeneratePostXML(Guid.NewGuid(), cn , AppSN , AppHRID , AppHRName , AppDate , AppDept , AppCompany , EmpID , EmpName , LeaveID , LeaveName , LeaveTypeID , FromDate , ToDate , DayInt , HourInt , reasonWhyNote + suggestionMsg + "\n\r" + strFromClient , strAttachment , isSkyWorth ); #endregion PostResult result = BPMProcess.Post(cn, xmlStream); String DisplayName = result.Recipients[0].Owner.DisplayName; //JsonItem JosonRv = new JsonItem(); JosonRv.Attributes.Add("success", true); JosonRv.Attributes.Add("successMessage", "\n\r <BR> 流程【" + result.SN + "】\n\r <BR> 成功提交给 " + DisplayName); context.Response.Write(JosonRv.ToString()); } } else { String strMsg = String.Format(JosonStrings.Aspx_UnknowCommand, method); //JsonItem JosonRv = new JsonItem(); JosonRv.Attributes.Add("success", false); JosonRv.Attributes.Add("errorMessage", strMsg); context.Response.Write(JosonRv.ToString()); throw new Exception(strMsg); } //System.Threading.Thread.Sleep(500); } catch (Exception e) { JsonItem JosonRv = new JsonItem(); JosonRv.Attributes.Add("success", false); JosonRv.Attributes.Add("errorMessage", e.Message); context.Response.Write(JosonRv.ToString()); } }
public void ProcessRequest(HttpContext context) { YZAuthHelper.OAuth(); //YZAuthHelper.AshxAuthCheck(); string method = context.Request.Params["method"]; if (method == "GetUsers") { string keyword = context.Request.Params["keyword"]; keyword = string.IsNullOrEmpty(keyword) ? "ASDT" : keyword; //获得数据 UserCollection users = new UserCollection(); int rowcount; JsonItem rootItem = new JsonItem(); using (BPMConnection cn = new BPMConnection()) { cn.WebOpen(); users = OrgSvr.SearchUser(cn, keyword); List <User> usersLst = users.Where(s => s.NameSpace == "LDAP").ToList <User>(); //usersLst = users.Where(s => s.ExtAttributes["Supplayer"]=="SDT").ToList<User>(); //usersLst = users.Select(u => u.ExtAttributes["Supplayer"] == "").ToList<User>(); usersLst.Sort(new UserCompare()); rowcount = usersLst.Count; //将数据转化为Json集合 rootItem.Attributes.Add(JsonItem.TotalRows, rowcount); JsonItemCollection children = new JsonItemCollection(); rootItem.Attributes.Add("children", children); rootItem.Attributes.Add("total", rowcount); int i = 0; foreach (User user in usersLst) { i++; //if (i > 8) // break; if (user.Account == "sa") { continue; } JsonItem item = new JsonItem(); children.Add(item); item.Attributes.Add("Name", user.DisplayName); item.Attributes.Add("Account", user.Account); item.Attributes.Add("HRID", user.HRID); item.Attributes.Add("user", user.ShortName); item.Attributes.Add("group", YZPinYinHelper.GetShortPinyin(user.ShortName.Substring(0, 1)).ToUpper()); item.Attributes.Add("Mobile", user.Mobile); item.Attributes.Add("HomePhone", user.HomePhone); item.Attributes.Add("OfficePhone", user.OfficePhone); item.Attributes.Add("Mail", user.EMail); } } //输出数据 context.Response.Write(rootItem.ToString()); } else if (method == "GetUser") { string uid = context.Request.Params["uid"]; JsonItem rv = new JsonItem(); if (!String.IsNullOrEmpty(uid)) { using (BPMConnection cn = new BPMConnection()) { JsonItem data = new JsonItem(); rv.Attributes.Add("data", data); cn.WebOpen(); User user = User.FromAccount(cn, uid); data.Attributes["Account"] = user.Account; data.Attributes["HRID"] = user.HRID; data.Attributes["DisplayName"] = user.ShortName; data.Attributes["Mobile"] = user.Mobile; data.Attributes["OfficePhone"] = user.OfficePhone; data.Attributes["HomePhone"] = user.HomePhone; data.Attributes["EMail"] = user.EMail; data.Attributes["Office"] = user.Office; data.Attributes["Birthday"] = YZStringHelper.DateToString(user.Birthday); data.Attributes["DateHired"] = YZStringHelper.DateToString(user.DateHired); data.Attributes["Desc"] = user.Description; //获得所有主管 BPMObjectNameCollection depts = new BPMObjectNameCollection(); UserCollection supervisors = new UserCollection(); MemberCollection members = OrgSvr.GetUserPositions(cn, uid); foreach (Member member in members) { OU ou = member.GetParentOU(cn); String OULevel = ou.OULevel; String OUName = ou.Name; String FullName = member.GetParentOU(cn).FullName; String mFullName = member.FullName; String mDepartment = member.Department; if (!ou.IsRootOU) { OUName = mFullName.Split(new char[2] { '/', '/' })[2].GetShortName().ToString(); depts.Add(OUName); } if (String.IsNullOrEmpty(member.LeaderTitle)) { depts.Add(ou.Name); } else { depts.Add(ou.Name); } //depts.Add(String.Format("{0}({1})", ou.Name, member.LeaderTitle)); SupervisorCollection spvs = Member.GetSupervisors(cn, member.FullName); foreach (Supervisor spv in spvs) { User spvUser = User.TryGetUser(cn, spv.UserAccount); if (spvUser == null) { spvUser = new User(); spvUser.Account = spv.UserAccount; } spv.UserFullName = YZStringHelper.GetUserShortName(spvUser.Account, spvUser.DisplayName); if (!supervisors.Contains(spvUser.Account)) { supervisors.Add(spvUser); } } } JsonItemCollection jsonSupervisors = new JsonItemCollection(); data.Attributes["Supervisors"] = jsonSupervisors; foreach (User spv in supervisors) { JsonItem jsonSupervisor = new JsonItem(); jsonSupervisors.Add(jsonSupervisor); jsonSupervisor.Attributes["uid"] = spv.Account; jsonSupervisor.Attributes["ShortName"] = spv.ShortName; } data.Attributes["Dept"] = String.Join(" > ", depts.ToArray()); } } rv.Attributes.Add("success", true); context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); // 响应类型 context.Response.AppendHeader("Access-Control-Allow-Methods", "POST"); // 响应头设置 context.Response.AppendHeader("Access-Control-Allow-Headers", "x-requested-with,content-type"); context.Response.Charset = "gb2312"; //设置字符集类型 context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); context.Response.ContentType = "application/json;charset=gb2312"; context.Response.Write(rv.ToString()); } }
protected override void OnPreRender(EventArgs e) { using (BPMConnection cn = new BPMConnection()) { cn.WebOpen(); BPM.Client.User user = BPM.Client.User.FromAccount(cn, YZAuthHelper.LoginUserAccount); UserInfoSelfMantSetting setting = new UserInfoSelfMantSetting(); setting.Load(cn); this._labUser.Text = HttpUtility.HtmlEncode(YZStringHelper.GetUserFriendlyName(user.Account, user.DisplayName)); this._txtFullName.Text = user.DisplayName; this._txtDesc.Text = user.Description; if (user.Sex != Sex.Unknown) { this._rdoSex.SelectedValue = user.Sex.ToString(); } this._txtBirthday.Text = YZStringHelper.DateToString(user.Birthday); this._txtHRID.Text = user.HRID; this._txtDateHired.Text = YZStringHelper.DateToString(user.DateHired); this._txtOffice.Text = user.Office; this._txtCostCenter.Text = user.CostCenter; this._txtPhone.Text = user.OfficePhone; this._txtHomePhone.Text = user.HomePhone; this._txtMobile.Text = user.Mobile; this._txtEMail.Text = user.EMail; this._txtWebSite.Text = user.WWWHomePage; List <WebControl> diasbleControls = new List <WebControl>(); if (!setting.CanWrite(UserProperty.DisplayName)) { diasbleControls.Add(this._txtFullName); } if (!setting.CanWrite(UserProperty.Description)) { diasbleControls.Add(this._txtDesc); } if (!setting.CanWrite(UserProperty.Sex)) { diasbleControls.Add(this._rdoSex); } if (!setting.CanWrite(UserProperty.Birthday)) { diasbleControls.Add(this._txtBirthday); } if (!setting.CanWrite(UserProperty.HRID)) { diasbleControls.Add(this._txtHRID); } if (!setting.CanWrite(UserProperty.DateHierd)) { diasbleControls.Add(this._txtDateHired); } if (!setting.CanWrite(UserProperty.Office)) { diasbleControls.Add(this._txtOffice); } if (!setting.CanWrite(UserProperty.CostCenter)) { diasbleControls.Add(this._txtCostCenter); } if (!setting.CanWrite(UserProperty.OfficePhone)) { diasbleControls.Add(this._txtPhone); } if (!setting.CanWrite(UserProperty.HomePhone)) { diasbleControls.Add(this._txtHomePhone); } if (!setting.CanWrite(UserProperty.Mobile)) { diasbleControls.Add(this._txtMobile); } if (!setting.CanWrite(UserProperty.EMail)) { diasbleControls.Add(this._txtEMail); } if (!setting.CanWrite(UserProperty.WWWHomePage)) { diasbleControls.Add(this._txtWebSite); } foreach (WebControl control in diasbleControls) { control.Attributes["disabled"] = "disabled"; control.CssClass = "form-input form-input-disabled"; } } base.OnPreRender(e); }
public void ProcessRequest(HttpContext context) { try { YZAuthHelper.OAuth(); //YZAuthHelper.AshxAuthCheck(); string method = context.Request.Params["Method"]; JsonItem rv = new JsonItem(); if (YZStringHelper.EquName(method, "GET")) { string uid = YZAuthHelper.LoginUserAccount; using (BPMConnection cn = new BPMConnection()) { JsonItem data = new JsonItem(); rv.Attributes.Add("data", data); cn.WebOpen(); User user = User.FromAccount(cn, uid); UserInfoSelfMantSetting setting = new UserInfoSelfMantSetting(); setting.Load(cn); data.Attributes["Account"] = user.Account; data.Attributes["HRID"] = user.HRID; data.Attributes["DisplayName"] = user.DisplayName; data.Attributes["Mobile"] = user.Mobile; data.Attributes["OfficePhone"] = user.OfficePhone; data.Attributes["HomePhone"] = user.HomePhone; data.Attributes["EMail"] = user.EMail; data.Attributes["Office"] = user.Office; data.Attributes["Birthday"] = YZStringHelper.DateToString(user.Birthday); data.Attributes["DateHired"] = YZStringHelper.DateToString(user.DateHired); data.Attributes["editableFields"] = "DisplayName,HRID,Mobile,OfficePhone,HomePhone,EMail,Office,Birthday,DateHired"; //data.Attributes["editableFields"] = "Mobile,OfficePhone,HomePhone,EMail,Office"; //获得所有主管 BPMObjectNameCollection depts = new BPMObjectNameCollection(); BPMObjectNameCollection supervisors = new BPMObjectNameCollection(); MemberCollection members = OrgSvr.GetUserPositions(cn, uid); foreach (Member member in members) { OU ou = member.GetParentOU(cn); depts.Add(ou.Name); SupervisorCollection spvs = Member.GetSupervisors(cn, member.FullName); foreach (Supervisor spv in spvs) { if (!supervisors.Contains(spv.UserFriendlyName)) { supervisors.Add(spv.UserFriendlyName); } } } data.Attributes["Supervisor"] = String.Join(",", supervisors.ToArray()); data.Attributes["Dept"] = String.Join(",", depts.ToArray()); } } else if (YZStringHelper.EquName(method, "UPDATE")) { string uid = YZAuthHelper.LoginUserAccount; string fieldName = context.Request.Params["fieldName"]; string strValue = context.Request.Params["value"]; DateTime date; using (BPMConnection cn = new BPMConnection()) { cn.WebOpen(); User user = User.FromAccount(cn, uid); switch (fieldName) { case "DisplayName": user.DisplayName = strValue; break; case "HRID": user.HRID = strValue; break; case "Mobile": user.Mobile = strValue; break; case "OfficePhone": user.OfficePhone = strValue; break; case "HomePhone": user.HomePhone = strValue; break; case "EMail": user.EMail = strValue; break; case "Office": user.Office = strValue; break; case "Birthday": if (DateTime.TryParse(strValue, out date)) { user.Birthday = date; } else { user.Birthday = DateTime.MinValue; } break; case "DateHired": if (DateTime.TryParse(strValue, out date)) { user.DateHired = date; } else { user.DateHired = DateTime.MinValue; } break; } User.Update(cn, uid, user); } } else { throw new Exception(String.Format(JosonStrings.Aspx_UnknowCommand, method)); } //System.Threading.Thread.Sleep(500); rv.Attributes.Add("success", true); context.Response.Write(rv.ToString()); } catch (Exception e) { JsonItem rv = new JsonItem(); rv.Attributes.Add("success", false); rv.Attributes.Add("errorMessage", e.Message); context.Response.Write(rv.ToString()); } context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); // 响应类型 context.Response.AppendHeader("Access-Control-Allow-Methods", "POST"); // 响应头设置 context.Response.AppendHeader("Access-Control-Allow-Headers", "x-requested-with,content-type"); context.Response.Charset = "gb2312"; //设置字符集类型 context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); context.Response.ContentType = "application/json;charset=gb2312"; }
public virtual JObject GenExcelReport(HttpContext context) { YZRequest request = new YZRequest(context); string excelTemplate = request.GetString("ExcelFile"); Dictionary <string, string> reportParams = new Dictionary <string, string>(); //获得查询参数 string strUserParamNames = request.GetString("UserParamNames", null); if (!String.IsNullOrEmpty(strUserParamNames)) { string[] paramNames = strUserParamNames.Split(','); foreach (string paramName in paramNames) { reportParams.Add(paramName, request.GetString(paramName, null)); } } //传递页信息 reportParams.Add("RowNumStart", request.RowNumStart.ToString()); reportParams.Add("RowNumEnd", request.RowNumEnd.ToString()); //打开文件 HSSFWorkbook book; using (FileStream file = new FileStream(context.Server.MapPath(excelTemplate), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { book = new HSSFWorkbook(file); } //填充数据 DataSet dataset = YZExcelGenerate.Fill(book, reportParams, null); YZExcelGenerate.PrepareForOutput(book); //调试输出 //using (FileStream fs = new FileStream(@"e:\abc.xls", FileMode.Create)) //{ // book.Write(fs); // fs.Close(); //} string outputType = context.Request.Params["outputType"]; if (outputType == "Export") //导出 { //Excel文件保存到流 byte[] bytes; using (MemoryStream ms = new MemoryStream()) { book.Write(ms); bytes = ms.ToArray(); } //设置Response头 string fileName = String.Format("{0}-{1}{2}", Path.GetFileNameWithoutExtension(excelTemplate), YZStringHelper.DateToString(DateTime.Now), Path.GetExtension(excelTemplate)); context.Response.Clear(); context.Response.ContentType = "application/vnd.ms-excel"; context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); context.Response.AppendHeader("Content-Length", bytes.Length.ToString()); context.Response.BinaryWrite(bytes); context.Response.End(); return(null); } else { JObject rv = new JObject(); book.GetSheetAt(0).DisplayGridlines = false; using (MemoryStream stream = new MemoryStream()) { book.Write(stream); string htmlFile = FileConvert.Excel2Html(stream, Path.GetExtension(excelTemplate)); rv["htmlFile"] = Path.GetFileName(htmlFile); //模拟输出一个store rv[YZJsonProperty.total] = 0; JArray children = new JArray(); rv["children"] = children; foreach (DataTable table in dataset.Tables) { if (table.Columns.Contains("TotalRows")) { int totalRows = 0; if (table.Rows.Count == 0) { totalRows = 0; } else { totalRows = Convert.ToInt32(table.Rows[0]["TotalRows"]); } rv[YZJsonProperty.total] = totalRows; children = new JArray(); rv["children"] = children; JObject item = new JObject(); children.Add(item); for (int i = 0; i < table.Rows.Count; i++) { item["id"] = i; } break; } } return(rv); } } }