<%@ WebHandler Language="C#" Class="CustomPageDisplay" Debug="true" %> using System; using System.Collections.Generic; using System.Web; using System.Data; using System.IO; using eMIS.Data; using System.Data.Common; using System.Web.SessionState; using eMIS; using System.Text; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using Newtonsoft.Json.Linq; public class CustomPageDisplay : IHttpHandler, IRequiresSessionState { private HttpContext context = null; Dictionary cflist = new Dictionary(); public void ProcessRequest (HttpContext context) { this.context = context; FileStream fs = File.OpenRead(context.Server.MapPath("app/exporttemplate.xls")); HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs); fs.Close(); ISheet sheet = hssfworkbook.GetSheetAt(0); string programId = context.Request.QueryString["pid"].ToString(); string recordId = context.Request.QueryString["rid"].ToString(); StringBuilder sb = new StringBuilder(); InstanceManager inst = new InstanceManager(context,programId); DataTable table; if (recordId == "") table = inst.GetListConfigurationTable(); else table = inst.BusinessDbOperator.ExecuteTable("select " + inst.Program.ListSqlSelect + " from " + inst.Program.ListTableName + " where "+inst.Program.PrimaryKey + " in (" + recordId + ") " + inst.GetSqlOrderBy()); if (table.Rows.Count > 10000) { context.Response.Redirect("export_csv3.ashx?pid="+programId+"&rid="); context.Response.End(); } DataTable elements = inst.Program.ListElements; int elementsCount = elements.Rows.Count; int i,j; bool merge = false; JObject jobj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject("{" + inst.Program.Properties["json"].ToString() + "}"); if (jobj["exp"] != null) { jobj = (JObject)jobj["exp"]; merge = (bool)jobj["merge"]; } IRow row = sheet.CreateRow(0); ICell cell; IDataFormat dataformat = hssfworkbook.CreateDataFormat(); ICellStyle style_num = hssfworkbook.CreateCellStyle(); style_num.DataFormat = dataformat.GetFormat("0"); string[,] values = new string[elementsCount,2]; ICellStyle style1 = null; string f; string[] a; CFormat cf = new CFormat(); for (i = 0; i < elementsCount; i++) { values[i,0] = "null"; values[i,1] = "0"; cell = row.CreateCell(i); cell.SetCellValue(elements.Rows[i]["kjms"].ToString()); f=GetFormatDesc(elements.Rows[i]["ys"].ToString()); if (f != "") { cf = new CFormat(); a=f.Split(','); style1 = hssfworkbook.CreateCellStyle(); style1.DataFormat = GetFormat(dataformat, a[0], a[1]); if (a[0] == "number") { cf.ditig = int.Parse(a[1].Substring(1)); } cf.style = style1; cflist.Add("s" + i.ToString(), cf); } } // System.Text.RegularExpressions.Regex rex=new System.Text.RegularExpressions.Regex(@"^\d+$"); ControlManager control = new ControlManager(inst); string s; string s0=""; string preS0=""; int c=table.Rows.Count; int num=0; string expType; int digit; for (j = 0; j < c;j++ ) { row = sheet.CreateRow(j+1); for ( i = 0; i < elementsCount; i++) { cell = row.CreateCell(i); control.Init(table.Rows[j], elements.Rows[i]); expType = control.GetParamValue("exptype", ""); s = control.Text; if (i == 0) s0 = s; //context.Response.Write(s + "====="); /* if(control.GetParamValue("expisnum","")=="1") //if (rex.IsMatch(s)) { //sb.Append("'"); } else { s = s.Replace("\r", " "); s = s.Replace("\n", " "); //s = s.Replace("\"", "\"\""); s = s.Replace(",", ","); s = s.Replace("'", "’"); } * */ if (s != "" && elements.Rows[i]["kjlx"].ToString()!="3" && !elements.Rows[i]["qzzd"].ToString().Contains("$") && elements.Rows[i]["gxzd"].ToString()=="" && elements.Rows[i]["qzzdlx"].ToString() == "2") { try { if (cflist.ContainsKey("s" + i.ToString())) { digit = cflist["s" + i.ToString()].ditig; cell.CellStyle = cflist["s" + i.ToString()].style; } else { style1 = hssfworkbook.CreateCellStyle(); cf = GetDigit(style1, dataformat,i.ToString(),s); cell.CellStyle = style1; digit = cf.ditig; } cell.SetCellValue((double)Math.Round(double.Parse(s), digit)); } catch(Exception exc) { context.Response.Write(control.ControlDescription+ " : " +s + "===" + i); context.Response.End(); } } else { if (expType!="string" && s != "" && DataManager.IsNumber(s) && s.Length<=15) { cell.CellStyle = style_num; try { cell.SetCellValue(ulong.Parse(s)); } catch (Exception exc ) { context.Response.Write(s + " : " + exc.Message); context.Response.End(); } } else { cell.SetCellValue(s); } } num = int.Parse(values[i, 1]); if (s0==preS0 &&s == values[i, 0]) { values[i, 1] = (num + 1).ToString(); } else { //并合 values[i, 0] = s; //当前行j+1; if (num > 0) { if (merge) sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(j-num,j, i, i)); } values[i, 1] = "0"; } if (j == c - 1) { num = int.Parse(values[i, 1]); if (num > 0) { if (merge) sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(j+1-num,j+1, i, i)); } } preS0 = s0; } } //context.Response.End(); context.Response.AddHeader("Content-Disposition", "attachment; filename=export.xls"); context.Response.ContentType = "application/octet-stream"; context.Response.BinaryWrite(WriteToStream(hssfworkbook).GetBuffer()); //context.Response.ContentEncoding = Encoding.GetEncoding("gb2312"); //context.Response.Write(sb.ToString()); //context.Response.Flush(); hssfworkbook.Close(); context.Response.End(); } private CFormat GetDigit(ICellStyle style,IDataFormat dataformat, string idx, string v) { //"0.00"; int d = 0; int i = v.IndexOf("."); if (i != -1) d = v.Length - i - 1; string r = "0"; for (i = 0; i < d; i++) r += (i == 0 ? "." : "") + "0"; style.DataFormat = dataformat.GetFormat(r); CFormat cf = new CFormat(); cf.style = style; cf.ditig = d; cflist.Add("s" + idx, cf); return cf; } private short GetFormat(IDataFormat dataformat,string type,string d) { short r=-1; switch(type) { case "number": r = dataformat.GetFormat(GetNumberFormat(d)); break; } return r; } private string GetNumberFormat(string f) { //f="f2" string r = "0.00"; if (f == "f2") return r; string head = f.Substring(0, 1); int c = int.Parse(f.Substring(1)); if (head == "f") { r = "0."; for (int i = 0; i < c; i++) r += "0"; } return r; } private string GetFormatDesc(string formatString) { int i = formatString.IndexOf("format:("); if (i == -1) return ""; string s = formatString.Substring(i + 8, formatString.IndexOf(")", i) - i - 8); return s; } private MemoryStream WriteToStream(HSSFWorkbook hssfworkbook) { //Write the stream data of workbook to the root directory MemoryStream file = new MemoryStream(); hssfworkbook.Write(file); return file; } public bool IsReusable { get { return false; } } } public class CFormat { public int ditig = 0; public ICellStyle style = null; }