C# 利用NPOI 實現Excel轉html


 由於直接生成的表格樣式很丑,添加了給頁面加css的步驟

頁面輸出方式新增一種,可避免輸入filename參數和生成html文件

 

    public void ExcelToHtml(string fileName, IWorkbook workbook)
    {
        ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter();

        // 設置輸出參數
        excelToHtmlConverter.OutputColumnHeaders = true;
        excelToHtmlConverter.OutputHiddenColumns = false;
        excelToHtmlConverter.OutputHiddenRows = false;
        excelToHtmlConverter.OutputLeadingSpacesAsNonBreaking = true;
        excelToHtmlConverter.OutputRowNumbers = true;
        excelToHtmlConverter.UseDivsToSpan = true;

        // 處理的Excel文件
        excelToHtmlConverter.ProcessWorkbook(workbook);
        //添加表格樣式
        excelToHtmlConverter.Document.InnerXml =
            excelToHtmlConverter.Document.InnerXml.Insert(
                excelToHtmlConverter.Document.InnerXml.IndexOf("<head>", 0) + 6,
                @"<style>table, td, th{border:1px solid green;}th{background-color:green;color:white;}</style>"
            );

        //方法一
        return Content(excelToHtmlConverter.Document.InnerXml);

        //方法二
        ////輸出的html文件   需創建對應的文件目錄  這里是根目錄下的doc文件夾
        //var htmlFile = System.Web.HttpContext.Current.Server.MapPath("/") + "doc\\" + fileName + ".html";
        //excelToHtmlConverter.Document.Save(htmlFile);

        //Response.Redirect("http://" + System.Web.HttpContext.Current.Request.Url.Host + ":" +
        //    System.Web.HttpContext.Current.Request.Url.Port + "/doc/" + fileName + ".html");
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM