NPOI를 사용하여 TABLE 컨텐트를 EXCEL로 내보내기

9589 단어 Excel
프로젝트에서 페이지의 테이블 내용을 EXCEL로 내보내야 합니다. 몇 가지 방법을 사용한 후에 NPO가 가장 빠르고 가장 좋은 것을 발견했습니다.
NPOI를 적용해야 합니다.dll 그리고 Ionic.Zip.dll이 쓸모가 있는지 없는지 연구하지 않아서 두 개의 DLL을 모두 bin 디렉터리에 넣었다
NPOIX dll 클릭 다운로드
페이지에
가 있다고 가정하십시오...
EXCEL로 내보내기 필요
페이지에 button 추가
<input type="button" name="excelBut" value="  Excel" onclick="toExcel()" class="sgbtn" /> 

페이지의 임의 부분에 자바스크립트를 삽입합니다:
function toExcel()

{

    post("tools/toExcel.aspx", {act:'tabletoexcel', html:$('.excelTable').html() });

}

function post(URL, PARAMS) {

    var temp = document.createElement("form");

    temp.action = URL;

    temp.method = "post";

    temp.style.display = "none";

    for (var x in PARAMS) {

        var opt = document.createElement("textarea");

        opt.name = x;

        opt.value = PARAMS[x];

        temp.appendChild(opt);

    }

    document.body.appendChild(temp);

    temp.submit();

    return temp;

} 
toExcel.aspx      
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="toExcel.aspx.cs" Inherits="tools_toExcel" %>

 
toExcel.aspx.cs    :
using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Text;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;



using NPOI.HSSF.UserModel;

using NPOI.HPSF;

using NPOI.POIFS.FileSystem;

using NPOI.HSSF.Util;

using System.Text.RegularExpressions;

using System.IO;



public partial class tools_toExcel : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        string act = GetValue("act");



        //toExcel.aspx?act=tabletoexcel&html=<table class="reportstable">..</table>

        if (act == "tabletoexcel")

        {

            TableToExcel();

        }

    }



    public void TableToExcel()

    {

        string tableHtml = Request.Form["html"];    //    table      

        if (string.IsNullOrEmpty(tableHtml)) { return; }



        InitializeWorkbook();

        HSSFSheet sheet1 = (HSSFSheet)hssfworkbook.CreateSheet("Sheet1");



        string rowContent = string.Empty;

        MatchCollection rowCollection = Regex.Matches(tableHtml, @"<tr[^>]*>[\s\S]*?<\/tr>", 

            RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); // tr    



        NPOI.SS.UserModel.IFont fontSubTitle = hssfworkbook.CreateFont();

        fontSubTitle.Boldweight = 800;//  



        NPOI.SS.UserModel.IFont fontBody = hssfworkbook.CreateFont();

        fontBody.Boldweight = 500;//  



        for (int i = 0; i < rowCollection.Count; i++)

        {

            HSSFRow row = (HSSFRow)sheet1.CreateRow(i);

            rowContent = rowCollection[i].Value;



            MatchCollection columnCollection = Regex.Matches(rowContent, @"<th[^>]*>[\s\S]*?<\/th>", 

                RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); // td    

            for (int td = 0; td < columnCollection.Count; td++)

            {               

                row.CreateCell(td).SetCellValue(StrTools.HtmlToTxt(columnCollection[td].Value));

            }



            columnCollection = Regex.Matches(rowContent, @"<td[^>]*>[\s\S]*?<\/td>", 

                RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); // td    

            for (int td = 0; td < columnCollection.Count; td++)

            {

                row.CreateCell(td).SetCellValue(StrTools.HtmlToTxt(columnCollection[td].Value));

            }

        }

        WriteToFile();

        downFile(ppath);

    }



    static HSSFWorkbook hssfworkbook;

    public string ppath;



    public void WriteToFile()

    {

        string year = DateTime.Now.Year.ToString();

        ppath = HttpContext.Current.Server.MapPath(DateTime.Now.ToString("yyyyMMddmmss") + ".xls");

        FileStream file = new FileStream(ppath, FileMode.Create);

        hssfworkbook.Write(file);

        file.Close();

    }



    public void InitializeWorkbook()

    {

        hssfworkbook = new HSSFWorkbook();

        ////create a entry of DocumentSummaryInformation

        DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();

        dsi.Company = "company";

        hssfworkbook.DocumentSummaryInformation = dsi;

        ////create a entry of SummaryInformation

        SummaryInformation si = PropertySetFactory.CreateSummaryInformation();

        si.Subject = "xxx";

        hssfworkbook.SummaryInformation = si;

    }



    public void downFile(string ppath)

    {

        if (File.Exists(ppath))

        {

            Response.ClearHeaders();

            Response.Clear();

            Response.Expires = 0;

            Response.Buffer = true;

            Response.AddHeader("Accept-Language", "zh-cn");

            string name = System.IO.Path.GetFileName(ppath);

            System.IO.FileStream files = new FileStream(ppath, FileMode.Open, FileAccess.Read, FileShare.Read);

            byte[] byteFile = null;

            if (files.Length == 0)

            {

                byteFile = new byte[1];

            }

            else

            {

                byteFile = new byte[files.Length];

            }

            files.Read(byteFile, 0, (int)byteFile.Length);

            files.Close();

            File.Delete(files.Name);

            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));

            Response.ContentType = "application/octet-stream;charset=gbk";

            Response.BinaryWrite(byteFile);

            Response.End();

        }

    }



    /// <summary>

    /// POST/GET     

    /// </summary>

    /// <param name="context"></param>

    /// <param name="name"></param>

    /// <returns></returns>

    private string GetValue(string name)

    {

        string result = ConvertData.ConvertToString(Request.QueryString[name], "");

        if (string.IsNullOrEmpty(result))

        {

            result = ConvertData.ConvertToString(Request.Form[name], "");

        }

        return StrTools.SafeSqlstr(result);

    }

}


이렇게 하면 HTML의 TABLE를 편리하게 EXCEL로 내보낼 수 있어요~ 코드가 좀 어지러우니 개의치 마세요.

좋은 웹페이지 즐겨찾기