1. 程式人生 > >npoi根據html字串動態生成excel模板

npoi根據html字串動態生成excel模板

npoi多表頭資料匯出目前有兩種方法:

其一是根據excel模板來匯出資料

其二是npoi動態建立多表頭

上面的兩種方法我都用過今天我介紹的是根據html字串來建立excel,但是要設定響應的屬性,

其實也就是對應 npoi CellRangeAddress 方法所需要的四個引數(firstrow,lastrow,firstcol,lastcol),這四個引數代表的意思是 單元格的開始行索引,結束行索引,開始列索引,結束列索引。

先要有table表頭的字串然後用HtmlAgilityPack去解析。

table字串如下

    string [email protected]

"<table cords='3,7'>
        <tr>
            <td cords='0,2,0,0' rowspan='3'>111</td>
            <td cords='0,0,1,2' colspan='2'>222</td>
            <td cords='0,0,3,5' colspan='3'>5555</td>
            <td cords='0,2,6,6' rowspan='3'>888</td>
        </tr>
        <tr>
            <td cords='1,2,1,1' rowspan='2'>333</td>
            <td cords='1,2,2,2' rowspan='2'>444</td>
            <td cords='1,1,3,4' colspan='2'>666</td>
            <td cords='1,1,5,5'>777</td>
        </tr>
        <tr>
            <td cords='2,2,3,3'>6661</td>
            <td cords='2,2,4,4'>6662</td>
            <td cords='2,2,5,5'>771</td>
        </tr>
    </table>";

table上cords屬性值的3,7,代表建立的table有幾行幾列

td上的cords屬性值表示但是單元格合併所需要的四個值。

然後用npoi根據table的cords的值動態建立行和列然後根據td的cords來動態的合併單元格

完成程式碼如下:

    

    HtmlDocument doc = new HtmlDocument();
    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 = new HSSFWorkbook();
              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 = new MemoryStream();
             wk.Write(mstream);

            string fileName = "動態建立excel.xls";
            byte[] bytes = mstream.ToArray();
             mstream.Read(bytes, 0, bytes.Length);
             mstream.Close();
             System.Web.HttpContext.Current.Response.Clear();
             System.Web.HttpContext.Current.Response.ClearContent();
             System.Web.HttpContext.Current.Response.ClearHeaders();
             HttpContext.Current.Response.Charset = "UTF-8";
             System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
             System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
             System.Web.HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary"); System.Web.HttpContext.Current.Response.BinaryWrite(bytes);
             System.Web.HttpContext.Current.Response.Flush();
             System.Web.HttpContext.Current.Response.End();

 

原想直接根據td的rowspan 或者colspan來直接建立excel但是做了一下沒實現,就只有加個自定義的屬性來實現了,如有更好的方法請留言討論。

如需轉載請儲存原文連線