码迷,mamicode.com
首页 > 其他好文 > 详细

NPOI分层导出

时间:2016-08-10 20:55:25      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

技术分享
  1 using NPOI.HSSF.UserModel;
  2 using NPOI.POIFS.FileSystem;
  3 using org.in2bits.MyXls;
  4 using System;
  5 using System.Collections.Generic;
  6 using System.Data;
  7 using System.IO;
  8 using System.Linq;
  9 using System.Text;
 10 using System.Web;
 11 using System.Web.UI;
 12 using System.Web.UI.WebControls;
 13 using Topevery.Basis.Config;
 14 using Topevery.Basis.Logic;
 15 using Topevery.DUM.Entity;
 16 
 17 namespace Topevery.DUM.Report.PublicCaseAnalysis
 18 {
 19     public partial class EvtSpread : BasePage
 20     {
 21         protected void Page_Load(object sender, EventArgs e)
 22         {
 23             if (!this.IsPostBack)
 24             {
 25                 //txtStartDate.Text = string.Format("{0}-{1}-1", DateTime.Today.Year, DateTime.Today.Month);
 26                 //txtEndDate.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Today);
 27                 txtStartDate.Text = "2015-01-01";
 28                 txtEndDate.Text = "2016-08-01";
 29             }
 30 
 31             AjaxPro.Utility.RegisterTypeForAjax(typeof(EvtSpread));
 32         }
 33 
 34         /// <summary>
 35         /// 分布统计查询
 36         /// </summary>
 37         /// <param name="evtPara"></param>
 38         /// <returns></returns>
 39         [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.Read)]
 40         public static EvtSpreadData GetZxEvtSpreadData(SearchPara evtPara)
 41         {
 42             EvtSpreadData result = new EvtSpreadData();
 43 
 44             //1.查出所有数据
 45             BaseParameter para = new BaseParameter();
 46 
 47             para.PageIndex = 1;
 48             para.PageSize = int.MaxValue;
 49 
 50 
 51             string title = "";
 52 
 53             //lblTitle.Text = string.Format("{0:yyyy-MM-01}至{1:MM-dd}{3}专项案件分布统计", DateTime.Today);
 54             if (!string.IsNullOrEmpty(evtPara.DateBegin))
 55             {
 56                 DateTime dtStart = DateTime.Now;
 57                 if (DateTime.TryParse(evtPara.DateBegin, out dtStart))
 58                 {
 59                     title += string.Format("{0:yyyy-MM-dd}—", dtStart);
 60                     para.BeginDate = dtStart;
 61                 }
 62             }
 63 
 64             if (!string.IsNullOrEmpty(evtPara.DateEnd))
 65             {
 66                 DateTime dtEnd = DateTime.Now;
 67                 if (DateTime.TryParse(evtPara.DateEnd, out dtEnd))
 68                 {
 69                     title += string.Format("{0:yyyy-MM-dd}", dtEnd);
 70                     para.EndDate = dtEnd.AddDays(1).AddSeconds(-1);
 71                 }
 72             }
 73 
 74 
 75             title += "案件分布统计";
 76 
 77             int recordCount = 0;
 78             DataTable dt = QmcgLogic.EvtSearchList(para);
 79             if (dt != null)
 80             {
 81                 recordCount = dt.Rows.Count;
 82             }
 83 
 84             StringBuilder StrbSprdHtm = new StringBuilder();
 85             string strTableClass = "TUI-grid-list";
 86             StrbSprdHtm.AppendFormat("<table class=‘{0}‘ ><colgroup ><col width=‘30px‘><col width=‘120px‘ /><col/><col/></colgroup><tr><th>序号</th><th class=‘AeraName ui-th-column‘>区域</th><th class=‘EvtCount ui-th-column‘>案件数</th></tr>", strTableClass);
 87 
 88             //循环各个区域
 89             Topevery.Basis.Entity.SysMapTreeCollection mapTreeColl = SysMapLogic.GetDefaultTree();
 90             if (mapTreeColl != null && mapTreeColl.Count > 0)
 91             {
 92                 foreach (Topevery.Basis.Entity.SysMapTree mapCity in mapTreeColl)
 93                 {
 94                     int iDistCount = 0;
 95                     //市下面的区循环
 96                     foreach (Topevery.Basis.Entity.SysMapTree mapDist in mapCity.Child)
 97                     {
 98                         iDistCount++;
 99                         string strDistTrStyle = "ui-widget-content jqgrow ui-row-ltr ui-priority-secondary";
100                         if (iDistCount % 2 == 1)
101                         {
102                             strDistTrStyle = "ui-widget-content jqgrow ui-row-ltr";
103                         }
104                         strDistTrStyle = string.Format("{0} {1}", Topevery.Basis.Config.MapTypeEnum.District, strDistTrStyle);
105                         if (dt.Rows.Count > 0)
106                         {
107                             //int prbInDistCount = 0;
108                             int evtInDistCount = GetEvtCountByMap(dt, mapDist.ID, Topevery.Basis.Config.MapTypeEnum.District);
109                             //
110                             StrbSprdHtm.AppendFormat("<tr class=‘{2}‘ mapId=‘{3}‘><td>{4}</td><td class=‘AeraName‘><a class=‘TUI-link-btn fl-left‘ href=‘javascript:void(0);‘ onclick=‘showOrHideStreet(this);‘><span class=‘ui-icon ui-icon-minus‘></span></a><a href=‘javascript:mapPositions({3})‘>{0}</a></td><td class=‘EvtCount‘><a href=‘javascript:void(0);‘ onclick=‘showDetail(this,{3},13002)‘>{1}</a></td></tr>", mapDist.Name, evtInDistCount, strDistTrStyle, mapDist.ID, iDistCount);
111 
112 
113                             if (evtInDistCount > 0)
114                             {
115                                 StrbSprdHtm.AppendFormat("<tr class=‘{0}_Out‘><td></td><td colspan=‘2‘ border=‘0‘>", MapTypeEnum.Street);
116                                 StrbSprdHtm.AppendFormat("<table class=‘{0}‘><colgroup ><col width=‘30px‘><col width=‘120px‘ /><col/><col/></colgroup><tr><th>序号</th><th class=‘AeraName ui-th-column‘>街道</th><th class=‘EvtCount ui-th-column‘>案件数</th></tr>", strTableClass);
117                                 int iStreetCount = 0;
118                                 //循环区下面的街道
119                                 foreach (Topevery.Basis.Entity.SysMapTree mapStreet in mapDist.Child)
120                                 {
121                                     string strStreetStyle = "ui-widget-content jqgrow ui-row-ltr ui-priority-secondary";
122                                     if (iStreetCount % 2 == 1)
123                                     {
124                                         strStreetStyle = "ui-widget-content jqgrow ui-row-ltr";
125                                     }
126                                     //int prbInStreetCount = 0;
127                                     int evtInStreetCount = GetEvtCountByMap(dt, mapStreet.ID, Topevery.Basis.Config.MapTypeEnum.Street);
128                                     if (evtInStreetCount > 0)
129                                     {
130                                         iStreetCount++;
131                                         StrbSprdHtm.AppendFormat("<tr class=‘{2}_Inner {5}‘ mapId=‘{3}‘><td>{6}</td><td class=‘AeraName‘><a class=‘TUI-link-btn fl-left‘ href=‘javascript:void(0);‘ onclick=‘showOrHideCmn(this);‘><span class=‘ui-icon ui-icon-plus‘></span></a><a href=‘javascript:mapPositions({3})‘>{0}</a></td><td class=‘EvtCount‘><a href=‘javascript:void(0);‘ onclick=‘showDetail(this,{3},13003)‘>{1}</a></td></tr><tr class=‘{4}_Out‘ style=‘display:none‘><td></td><td colspan=‘2‘>", mapStreet.Name, evtInStreetCount, MapTypeEnum.Street, mapStreet.ID, MapTypeEnum.Community, strStreetStyle, iStreetCount);
132                                         StrbSprdHtm.AppendFormat("<table class=‘{0}‘><colgroup><col width=‘30px‘><col width=‘120px‘ /><col/><col/></colgroup><tr><th>序号</th><th class=‘AeraName ui-th-column‘>社区</th><th class=‘EvtCount ui-th-column‘>案件数</th></tr>", strTableClass);
133 
134                                         int iCmnCount = 0;
135                                         //循环街道下面的社区
136                                         foreach (Topevery.Basis.Entity.SysMapTree mapComn in mapStreet.Child)
137                                         {
138                                             //int prbInCmnCount = 0;
139                                             int evtInCmnCount = GetEvtCountByMap(dt, mapComn.ID, Topevery.Basis.Config.MapTypeEnum.Community);
140                                             if (evtInCmnCount > 0)
141                                             {
142                                                 iCmnCount++;
143                                                 StrbSprdHtm.AppendFormat("<tr class=‘{2}_Inner‘ mapId=‘{3}‘><td>{4}</td><td class=‘AeraName‘><a href=‘javascript:mapPositions({3})‘>{0}</a></td><td class=‘EvtCount‘><a href=‘javascript:void(0);‘ onclick=‘showDetail(this,{3},13004)‘>{1}</a></td></tr>", mapComn.Name, evtInCmnCount, MapTypeEnum.Community, mapComn.ID, iCmnCount);
144                                             }
145 
146                                         }
147                                         StrbSprdHtm.Append("</table></td></tr>");
148                                     }
149                                 }
150                                 StrbSprdHtm.Append("</table>");
151                             }
152                             else
153                             {
154                                 StrbSprdHtm.AppendFormat("<tr class=‘{0}_Out‘ style=‘display:none;‘><td></td><td colspan=‘2‘ border=‘0‘>", MapTypeEnum.Street);
155                             }
156                             StrbSprdHtm.Append("</td></tr>");
157                         }
158                     }
159 
160                     StrbSprdHtm.Append("</table>");
161 
162                     StrbSprdHtm.Append("</td></tr>");
163                 }
164             }
165 
166             StrbSprdHtm.Append("</table>");
167 
168             result.SprHtmlResult = StrbSprdHtm.ToString();
169             result.Title = title;
170             //ExportQueryService.SetQueryVal(ExportEnumKey, para);
171             foreach (DataRow dr in dt.Rows)
172             {
173                 try
174                 {
175                     Evt evt = new Evt();
176                     evt.EvtId = Convert.ToInt64(dr["c_id"]);
177 
178                     try
179                     {
180                         evt.AbsX = Convert.ToDouble(dr["c_abs_x"]);
181 
182                         evt.AbsY = Convert.ToDouble(dr["c_abs_y"]);
183                     }
184                     catch { }
185 
186                     try
187                     {
188                         evt.DistId = Convert.ToInt32(dr["c_map_district_id"]);
189                         evt.StreetId = Convert.ToInt32(dr["c_map_street_id"]);
190                         evt.CmnId = Convert.ToInt32(dr["c_map_community_id"]);
191                     }
192                     catch { }
193 
194                     evt.Title = Convert.ToString(dr["c_title"]);
195 
196                     //evt.Status = Convert.ToInt32(dr["c_status"]);
197 
198                     result.ListEvt.Add(evt);
199                 }
200                 catch { }
201             }
202             return result;
203 
204         }
205 
206 
207 
208         /// <summary>
209         /// 导出excel文件
210         /// </summary>
211         /// <param name="reportTitle">标题</param>
212         /// <param name="dt">数据源</param>
213         /// <param name="columns">列名</param>
214         /// <param name="filePath">文件路径</param>
215         /// <param name="maxRow">一页显示最大记录数</param>
216         public static void SingleExport(string reportTitle, string subTitle, DataTable dt, Dictionary<string, string> columns, string filePath, int maxRow)
217         {
218             int WorkSheetCount = Convert.ToInt32(Math.Ceiling(dt.Rows.Count * 1.0 / maxRow));
219             XlsDocument doc = new XlsDocument();
220             for (int i = 0; i < WorkSheetCount; i++)
221             {
222                 Worksheet sheet = doc.Workbook.Worksheets.Add(string.Format("Sheet{0}", i + 1));
223 
224                 int rowIndex = 0;
225                 int colIndex = 0;
226                 int currentMinRowIndex = i * maxRow;
227                 int currentMaxRowIndex = 0;
228                 if (((i + 1) * maxRow + 1) < dt.Rows.Count)
229                     currentMaxRowIndex = (i + 1) * maxRow;
230                 else
231                     currentMaxRowIndex = dt.Rows.Count;
232 
233                 //标题
234                 if (!string.IsNullOrEmpty(reportTitle))
235                 {
236                     rowIndex++;
237 
238                     XF cellXF = doc.NewXF();
239                     cellXF.VerticalAlignment = VerticalAlignments.Centered;
240                     cellXF.HorizontalAlignment = HorizontalAlignments.Centered;
241                     cellXF.Font.Height = 24 * 12;
242                     cellXF.Font.Bold = true;
243                     //cellXF.Pattern = 1;//设定单元格填充风格。如果设定为0,则是纯色填充
244                     //cellXF.PatternBackgroundColor = Colors.EgaYellow;//填充的底色
245                     //cellXF.PatternColor = Colors.Grey;//设定填充线条的颜色
246 
247                     sheet.Cells.Add(rowIndex, 1, reportTitle, cellXF);
248                     MergeArea area = new MergeArea(1, 1, 1, columns.Count);
249                     sheet.AddMergeArea(area);
250                 }
251                 //副标题
252                 if (!string.IsNullOrEmpty(subTitle))
253                 {
254                     rowIndex++;
255 
256                     XF cellXF = doc.NewXF();
257                     cellXF.VerticalAlignment = VerticalAlignments.Centered;
258                     cellXF.HorizontalAlignment = HorizontalAlignments.Centered;
259 
260                     sheet.Cells.Add(rowIndex, 1, subTitle, cellXF);
261                     MergeArea area = new MergeArea(2, 2, 1, columns.Count);
262                     sheet.AddMergeArea(area);
263                 }
264 
265                 //列头标题
266                 rowIndex++;
267                 foreach (string colTitle in columns.Values)
268                 {
269                     colIndex++;
270 
271                     XF cellXF = doc.NewXF();
272                     cellXF.VerticalAlignment = VerticalAlignments.Centered;
273                     cellXF.HorizontalAlignment = HorizontalAlignments.Centered;
274                     cellXF.Font.Bold = true;
275                     cellXF.Pattern = 0;//设定单元格填充风格。如果设定为0,则是纯色填充
276                     cellXF.PatternBackgroundColor = Colors.Grey;//填充的底色
277 
278                     cellXF.TopLineColor = Colors.Black;
279                     cellXF.TopLineStyle = 1;
280                     cellXF.BottomLineColor = Colors.Black;
281                     cellXF.BottomLineStyle = 1;
282                     cellXF.LeftLineColor = Colors.Black;
283                     cellXF.LeftLineStyle = 1;
284                     cellXF.RightLineColor = Colors.Black;
285                     cellXF.RightLineStyle = 1;
286 
287                     sheet.Cells.Add(rowIndex, colIndex, colTitle, cellXF);
288 
289                 }
290 
291                 //数据行
292                 for (int j = currentMinRowIndex; j < currentMaxRowIndex; j++)
293                 {
294                     rowIndex++;
295                     colIndex = 0;
296 
297                     XF cellXF = doc.NewXF();
298                     cellXF.VerticalAlignment = VerticalAlignments.Centered;
299                     cellXF.HorizontalAlignment = HorizontalAlignments.Centered;
300 
301                     cellXF.TopLineColor = Colors.Black;
302                     cellXF.TopLineStyle = 1;
303                     cellXF.BottomLineColor = Colors.Black;
304                     cellXF.BottomLineStyle = 1;
305                     cellXF.LeftLineColor = Colors.Black;
306                     cellXF.LeftLineStyle = 1;
307                     cellXF.RightLineColor = Colors.Black;
308                     cellXF.RightLineStyle = 1;
309 
310                     foreach (string colName in columns.Keys)
311                     {
312                         colIndex++;
313                         object v = dt.Rows[j][colName];
314                         if (v is Int32 || v is Int16 || v is Int64 || v is Double || v is Single)
315                         {
316                             sheet.Cells.Add(rowIndex, colIndex, v == null || v == DBNull.Value ? "" : v, cellXF);
317                         }
318                         else
319                         {
320                             sheet.Cells.Add(rowIndex, colIndex, v == null || v == DBNull.Value ? "" : v.ToString(), cellXF);
321                         }
322                     }
323                 }
324             }
325 
326             doc.FileName = Guid.NewGuid().ToString() + ".xls";
327             if (!string.IsNullOrEmpty(filePath))
328             {
329                 doc.Save(filePath);
330             }
331             else
332             {
333 
334                 string folder = HttpContext.Current.Server.MapPath("~/Templates");
335 
336                 try
337                 {
338                     foreach (string file in System.IO.Directory.GetFiles(folder))
339                     {
340                         System.IO.FileInfo fi = new System.IO.FileInfo(file);
341                         if (DateTime.Now.Subtract(fi.CreationTime).TotalDays > 2)
342                         {
343                             System.IO.File.Delete(file);
344                         }
345                     }
346                 }
347                 catch { }
348                 doc.Save(folder);
349                 System.Web.HttpContext.Current.Response.WriteFile("~/Templates/" + doc.FileName);
350             }
351         }
352 
353         public const string ExportEnumKey = ExportKey.Regional;
354 
355         public static int GetEvtCountByMap(DataTable evtData, int mapId, Topevery.Basis.Config.MapTypeEnum mapType)
356         {
357             //prbCount = 0;
358             try
359             {
360                 string filter = "";
361                 switch (mapType)
362                 {
363                     case MapTypeEnum.District:
364                         filter = string.Format("[c_map_district_id]={0}", mapId);
365                         break;
366                     case MapTypeEnum.Street:
367                         filter = string.Format("[c_map_street_id]={0}", mapId);
368                         break;
369                     case MapTypeEnum.Community:
370                         filter = string.Format("[c_map_community_id]={0}", mapId);
371                         break;
372                 }
373 
374                 //object oPrbCount = evtData.Compute("sum([c_count])", filter);
375                 //try
376                 //{
377                 //    prbCount = Convert.ToInt32(oPrbCount);
378                 //}
379                 //catch { }
380                 return evtData.Select(filter).Length;
381             }
382             catch { }
383 
384             return 0;
385         }
386 
387         protected void Download_Click(object sender, EventArgs e)
388         {
389 
390             int recordCount = 0;
391             BaseParameter para = new BaseParameter();
392             string title = "";
393             if (!string.IsNullOrEmpty(txtStartDate.Text))
394             {
395                 DateTime dtStart = DateTime.Now;
396                 if (DateTime.TryParse(txtStartDate.Text, out dtStart))
397                 {
398                     title += string.Format("{0:yyyy-MM-dd}—", dtStart);
399                     para.BeginDate = dtStart;
400                 }
401             }
402             if (!string.IsNullOrEmpty(txtEndDate.Text))
403             {
404                 DateTime dtEnd = DateTime.Now;
405                 if (DateTime.TryParse(txtEndDate.Text, out dtEnd))
406                 {
407                     title += string.Format("{0:yyyy-MM-dd}", dtEnd);
408                     para.EndDate = dtEnd.AddDays(1).AddSeconds(-1);
409                 }
410             }
411             DataTable dt = QmcgLogic.EvtSearchList(para);
412             if (dt != null)
413             {
414                 recordCount = dt.Rows.Count;
415             }
416             List<string> subTitles = new List<string>();
417             Dictionary<string, string> cols = new Dictionary<string, string>();
418             DataTable dtnew = new DataTable("casetable");
419             dtnew.Columns.Add(new DataColumn("Id", typeof(Int32)));
420             dtnew.Columns.Add(new DataColumn("Region", typeof(string)));
421             dtnew.Columns.Add(new DataColumn("CaseNumber", typeof(Int32)));
422             dtnew.Columns.Add("c_level");
423             dtnew.Columns.Add("c_parent_id");
424             DataRow dr;
425             Topevery.Basis.Entity.SysMapTreeCollection mapTreeColl = SysMapLogic.GetDefaultTree();
426             if (mapTreeColl != null && mapTreeColl.Count > 0)
427             {
428 
429                 foreach (Topevery.Basis.Entity.SysMapTree mapCity in mapTreeColl)
430                 {
431                     int id = 0;
432                     int iDistCount = 0;
433                     //市下面的区循环
434                     foreach (Topevery.Basis.Entity.SysMapTree mapDist in mapCity.Child)
435                     {
436                         id++;
437                         iDistCount++;
438                         if (dt.Rows.Count > 0)
439                         {
440                             //区域案件数
441                             int evtInDistCount = GetEvtCountByMap(dt, mapDist.ID, Topevery.Basis.Config.MapTypeEnum.District);
442                             dr = dtnew.NewRow();
443                             dr["Id"] = mapDist.ID;
444                             dr["Region"] = mapDist.Name;
445                             dr["CaseNumber"] = evtInDistCount;
446                             dr["c_level"] = 1;
447                             dr["c_parent_id"] = 1;
448                             dtnew.Rows.Add(dr);
449                             //街道
450                             int iStreetCount = 0;
451                             if (evtInDistCount > 0)
452                             {
453                                 foreach (Topevery.Basis.Entity.SysMapTree mapStreet in mapDist.Child)
454                                 {
455                                     id++;
456                                     iStreetCount++;
457                                     //案件数
458                                     int StreetCount = GetEvtCountByMap(dt, mapStreet.ID, Topevery.Basis.Config.MapTypeEnum.Street);
459                                     dr = dtnew.NewRow();
460                                     dr["Id"] = mapStreet.ID;
461                                     //dr["Id"] = iStreetCount;
462                                     dr["Region"] = mapStreet.Name;
463                                     dr["CaseNumber"] = StreetCount;
464                                     dr["c_level"] = 2;
465                                     dr["c_parent_id"] = mapDist.ID;
466                                     dtnew.Rows.Add(dr);
467                                     //社区
468                                     int evtInStreetCount = GetEvtCountByMap(dt, mapStreet.ID, Topevery.Basis.Config.MapTypeEnum.Street);
469                                     if (evtInStreetCount > 0)
470                                     {
471                                         int iCmnCount = 0;
472                                         foreach (Topevery.Basis.Entity.SysMapTree mapComn in mapStreet.Child)
473                                         {
474                                             //案件数
475                                             int evtInCmnCount = GetEvtCountByMap(dt, mapComn.ID, Topevery.Basis.Config.MapTypeEnum.Community);
476                                             if (evtInCmnCount > 0)
477                                             {
478                                                 id++;
479                                                 iCmnCount++;
480                                                 dr = dtnew.NewRow();
481                                                 dr["Id"] = mapComn.ID;
482                                                 //dr["Id"] = iCmnCount;
483                                                 dr["Region"] = mapComn.Name;
484                                                 dr["CaseNumber"] = evtInCmnCount;
485                                                 dr["c_level"] = 3;
486                                                 dr["c_parent_id"] = mapStreet.ID;
487                                                 dtnew.Rows.Add(dr);
488                                                 Dictionary<string, string> CaseColumns = new Dictionary<string, string>();
489                                             }
490                                         }
491                                     }
492                                 }
493                             }
494                         }
495                     }
496                 }
497                 //-----------------------
498                 string filePath = System.IO.Path.Combine(Request.PhysicalApplicationPath, "tempFolder");
499                 filePath = System.IO.Path.Combine(filePath, Guid.NewGuid().ToString() + ".xls");
500                 HSSFWorkbook hssfWorkBook = new HSSFWorkbook();
501                 HSSFSheet sheet1 = hssfWorkBook.CreateSheet("Sheet1") as HSSFSheet;
502                 using (FileStream file = new FileStream(filePath, FileMode.Create))
503                 {
504                     hssfWorkBook.Write(file);
505                 }
506                 HSSFCellStyle _style = sheet1.Workbook.CreateCellStyle() as HSSFCellStyle;
507                 _style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
508                 _style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;
509 
510                 _style.BorderBottom = NPOI.SS.UserModel.CellBorderType.THIN;
511                 _style.BottomBorderColor = 64;
512 
513                 _style.BorderLeft = NPOI.SS.UserModel.CellBorderType.THIN;
514                 _style.LeftBorderColor = 64;
515 
516                 _style.BorderRight = NPOI.SS.UserModel.CellBorderType.THIN;
517                 _style.RightBorderColor = 64;
518 
519                 _style.BorderTop = NPOI.SS.UserModel.CellBorderType.THIN;
520                 _style.TopBorderColor = 64;
521                 DataRow[] drDists = dtnew.Select("c_level=1");
522                  sheet1.CreateRow(0);
523                  HSSFCell cell1 = sheet1.GetRow(0).CreateCell(0) as HSSFCell;
524                  HSSFCell cell2 = sheet1.GetRow(0).CreateCell(1) as HSSFCell;
525                  HSSFCell cell3 = sheet1.GetRow(0).CreateCell(2) as HSSFCell;
526                  cell1.SetCellValue("序号");
527                  cell2.SetCellValue("区域");
528                  cell3.SetCellValue("案件数");
529 
530                 foreach (DataRow drDist in drDists)
531                 {
532                     WriteExcelDataRowX(sheet1, dtnew, drDist, _style);
533                 }
534                 
535                 using (MemoryStream ms = new MemoryStream())
536                 {
537                     hssfWorkBook.Write(ms);
538                     Response.Charset = "utf-8";
539                     Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
540                     string titleString = string.Empty;
541                     if (Request.ServerVariables["http_user_agent"].ToLower().IndexOf("firefox") != -1)
542                     {
543                         titleString = "\"" + "区域案件分布统计表" + ".xls\"";
544                         Response.AddHeader("Content-Disposition", "attachment;filename=" + titleString);
545                     }
546                     else
547                     {
548                         Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", System.Web.HttpUtility.UrlEncode("区域案件分布统计表", System.Text.Encoding.UTF8) + ".xls"));
549                     }
550                     Response.BinaryWrite(ms.ToArray());
551 
552                     Response.End();
553                 }
554 
555 
556                 //********************************************************************************************************
557 
558             }
559         }
560 
561         void WriteExcelDataRowX(HSSFSheet sheet, DataTable allData, DataRow row, HSSFCellStyle style)
562         {
563             //NPOI向单元格写入值
564             //从此二行创建
565             int rowIndex = sheet.LastRowNum + 1;
566             sheet.CreateRow(rowIndex);
567             
568             for (int i = 0; i <= 2; i++)
569             {
570                 //HSSFCell cell1 = sheet.GetRow(rowIndex).CreateCell(i) as HSSFCell;
571                 //if (i == 0)
572                 //{
573                 //    cell1.SetCellValue("序号");
574                 //}
575                 //else if (i == 1)
576                 //{
577                 //    cell1.SetCellValue("区域");
578                 //}
579                 //else
580                 //{
581                 //    cell1.SetCellValue("案件数");
582                 //}
583                 HSSFCell cell = sheet.GetRow(rowIndex).GetCell(i) as HSSFCell;
584                 
585                 if (cell == null)
586                 {
587                     cell = sheet.GetRow(rowIndex).CreateCell(i) as HSSFCell;
588                     
589                 }
590                 cell.CellStyle = style;
591                 if (i==0)
592                 {
593                     //序号 
594                     cell.SetCellValue(Helper.GetDataValue(rowIndex, string.Empty));
595                 }
596                 else if (i==1)
597                 {
598                     //区域 
599                     cell.SetCellValue(Helper.GetDataValue(row["Region"], string.Empty));
600                 }
601                 else
602                 {
603                     //案件数 
604                     cell.SetCellValue(Helper.GetDataValue(row["CaseNumber"], string.Empty));
605                 }
606                
607             }
608 
609           
610             //next level
611             DataRow[] childData = allData.Select(string.Format("[c_parent_id]={0}", row["Id"]));
612           
613             if (childData != null && childData.Length > 0)
614             {
615                 int curIndex = sheet.LastRowNum;
616                 foreach (DataRow childRow in childData)
617                 {
618                     WriteExcelDataRowX(sheet, allData, childRow, style);
619                 }
620                 sheet.GroupRow(curIndex + 1, sheet.LastRowNum);
621             }
622         }
623     }
624 
625 
626 
627     [Serializable]
628     [AjaxPro.AjaxNoTypeUsage]
629     public class SearchPara
630     {
631         public string DateBegin;
632         public string DateEnd;
633         //public string EvtStatus;
634         //public int TaskId = 0;
635     }
636 
637     [Serializable]
638     [AjaxPro.AjaxNoTypeUsage]
639     public class EvtSpreadData
640     {
641         public List<Evt> ListEvt = new List<Evt>();
642 
643         public string SprHtmlResult = "";
644         public string Title = "";
645     }
646 
647     [Serializable]
648     [AjaxPro.AjaxNoTypeUsage]
649     public class Evt
650     {
651         public long EvtId;
652 
653         public double AbsX;
654 
655         public double AbsY;
656 
657         public string Title;
658 
659         public int DistId;
660         public int StreetId;
661         public int CmnId;
662 
663         //public int Status = 0;
664 
665         //public int FirstAttachType = -1;
666 
667         //public string PicGUID;
668 
669         //public string Html;
670     }
671 
672 
673 
674     
675 
676 }
View Code

 

NPOI分层导出

标签:

原文地址:http://www.cnblogs.com/xiaz/p/5758163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!