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");
    }

 

posted @ 2017-01-04 13:50  听雨的人  阅读(6303)  评论(10编辑  收藏  举报