npoi多表头数据导出目前有两种方法:
其一是根据excel模板来导出数据
其二是npoi动态创建多表头
上面的两种方法我都用过今天我介绍的是根据html字符串来创建excel,但是要设置响应的属性,
其实也就是对应 npoi CellRangeAddress 方法所需要的四个参数(firstrow,lastrow,firstcol,lastcol),这四个参数代表的意思是 单元格的开始行索引,结束行索引,开始列索引,结束列索引。
先要有table表头的字符串然后用HtmlAgilityPack去解析。
table字符串如下
string html=@"
111 | 222 | 5555 | 888 | |||
333 | 444 | 666 | 777 | |||
6661 | 6662 | 771 |
table上cords属性值的3,7,代表创建的table有几行几列
td上的cords属性值表示但是单元格合并所需要的四个值。
然后用npoi根据table的cords的值动态创建行和列然后根据td的cords来动态的合并单元格
完成代码如下:
HtmlDocument doc = newHtmlDocument();
doc.LoadHtml(html);
HtmlNode node=doc.DocumentNode;
HtmlNode div= node.SelectNodes("//table")[0];string[] strrowcol = div.Attributes["cords"].Value.Split(',');
HtmlNodeCollection hnc= node.SelectNodes("//table//tr");
HSSFWorkbook wk= newHSSFWorkbook();
ISheet tb= wk.CreateSheet("mySheet");
ICellStyle cellstyle=wk.CreateCellStyle();
cellstyle.Alignment=HorizontalAlignment.CENTER;
cellstyle.VerticalAlignment=VerticalAlignment.CENTER;
cellstyle.BorderBottom=CellBorderType.THIN;
cellstyle.BorderLeft=CellBorderType.THIN;
cellstyle.BorderRight=CellBorderType.THIN;
cellstyle.BorderTop=CellBorderType.THIN;for (int m = 0; m < int.Parse(strrowcol[0]); m++)
{
IRow rowb=tb.CreateRow(m);for (int n = 0; n < int.Parse(strrowcol[1]); n++)
{
ICell cell=rowb.CreateCell(n);
cell.CellStyle=cellstyle;
}
}for (int i = 0; i < hnc.Count; i++)
{
HtmlNodeCollection tdcount= hnc[i].SelectNodes("td");for (int y = 0; y < tdcount.Count; y++)
{string[] strs = tdcount[y].Attributes["cords"].Value.Split(','); tb.GetRow(int.Parse(strs[0])).GetCell(int.Parse(strs[2])).SetCellValue(tdcount[y].InnerText.Replace("\r\n", "").Trim());
tb.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(int.Parse(strs[0]), int.Parse(strs[1]), int.Parse(strs[2]), int.Parse(strs[3])));
}
}//这里可以添加数据也就是动态创建行和列然后填充数据//生成模板到excel
FileStream file= new FileStream(@"D:\CreateExcel.xls", FileMode.Create);
wk.Write(file);
file.Close();//不想生成的话可以直接下载
MemoryStream mstream= newMemoryStream();
wk.Write(mstream);string fileName = "动态创建excel.xls";byte[] bytes =mstream.ToArray();
mstream.Read(bytes,0, bytes.Length);
mstream.Close();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Charset= "UTF-8";
HttpContext.Current.Response.ContentType= "application/octet-stream";
Current.Response.AddHeader("Content-Disposition", "attachment; filename=" +fileName);
HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary"); HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
原想直接根据td的rowspan 或者colspan来直接创建excel但是做了一下没实现,就只有加个自定义的属性来实现了,如有更好的方法请留言讨论。
如需转载请保存原文连接