将HtmlTable内容导出到Excel,使用NPOI组件

      /// <summary>
        /// 将DataTable导出到Excel
        /// </summary>
        /// <param name="htmlTable">html表格内容</param>
        /// <param name="fileName">仅文件名(非路径)</param>
        /// <returns>返回Excel文件绝对路径</returns>
        public static string ExportHtmlTableToExcel(string htmlTable, string fileName)
        {
            string result;
            try
            {
                #region 第一步:将HtmlTable转换为DataTable
                htmlTable = htmlTable.Replace("\"", "'");
                var trReg = new Regex(pattern: @"(?<=(<[t|T][r|R]))[\s\S]*?(?=(</[t|T][r|R]>))");
                var trMatchCollection = trReg.Matches(htmlTable);
                DataTable dt = new DataTable("data");
                for (int i = 0; i < trMatchCollection.Count; i++)
                {
                    var row = "<tr " + trMatchCollection[i].ToString().Trim() + "</tr>";
                    var tdReg = new Regex(pattern: @"(?<=(<[t|T][d|D|h|H]))[\s\S]*?(?=(</[t|T][d|D|h|H]>))");
                    var tdMatchCollection = tdReg.Matches(row);
                    if (i == 0)
                    {
                        foreach (var rd in tdMatchCollection)
                        {
                            var tdValue = RemoveHtml("<td " + rd.ToString().Trim() + "</td>");
                            DataColumn dc = new DataColumn(tdValue);
                            dt.Columns.Add(dc);
                        }
                    }
                    if (i > 0)
                    {
                        DataRow dr = dt.NewRow();
                        for (int j = 0; j < tdMatchCollection.Count; j++)
                        {
                            var tdValue = RemoveHtml("<td " + tdMatchCollection[j].ToString().Trim() + "</td>");
                            dr[j] = tdValue;
                        }
                        dt.Rows.Add(dr);
                    }
                }
                #endregion

                #region 第二步:将DataTable导出到Excel
                result = "ok_" + ExportDataSetToExcel(dt, fileName);
                #endregion
            }
            catch (Exception ex)
            {
                result = "err_" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 将DataTable导出到Excel
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="fileName">仅文件名(非路径)</param>
        /// <returns>返回Excel文件绝对路径</returns>
        public static string ExportDataSetToExcel(DataTable dt, string fileName)
        {
            #region 表头
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            NPOI.SS.UserModel.Sheet hssfSheet = hssfworkbook.CreateSheet(fileName);
            hssfSheet.DefaultColumnWidth = 13;
            hssfSheet.SetColumnWidth(0, 25 * 256);
            hssfSheet.SetColumnWidth(3, 20 * 256);
            // 表头
            NPOI.SS.UserModel.Row tagRow = hssfSheet.CreateRow(0);
            tagRow.Height = 22 * 20;

            // 标题样式
            NPOI.SS.UserModel.CellStyle cellStyle = hssfworkbook.CreateCellStyle();
            cellStyle.Alignment = HorizontalAlignment.CENTER;
            cellStyle.VerticalAlignment = VerticalAlignment.CENTER;
            cellStyle.BorderBottom = CellBorderType.THIN;
            cellStyle.BorderBottom = CellBorderType.THIN;
            cellStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
            cellStyle.BorderLeft = CellBorderType.THIN;
            cellStyle.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
            cellStyle.BorderRight = CellBorderType.THIN;
            cellStyle.RightBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
            cellStyle.BorderTop = CellBorderType.THIN;
            cellStyle.TopBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;

            int colIndex;
            for (colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
            {
                tagRow.CreateCell(colIndex).SetCellValue(dt.Columns[colIndex].ColumnName);
                tagRow.GetCell(colIndex).CellStyle = cellStyle;
            }
            #endregion
            #region 表数据
            // 表数据
            for (int k = 0; k < dt.Rows.Count; k++)
            {
                DataRow dr = dt.Rows[k];
                NPOI.SS.UserModel.Row row = hssfSheet.CreateRow(k + 1);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    row.CreateCell(i).SetCellValue(dr[i].ToString());
                    row.GetCell(i).CellStyle = cellStyle;
                }
            }
            #endregion
            FileStream file = new FileStream(HttpContext.Current.Request.PhysicalApplicationPath + "Temp/" + fileName + ".xls", FileMode.Create);
            hssfworkbook.Write(file);
            file.Close();
            var basePath = VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath);
            return (basePath + "Temp/" + fileName + ".xls");
        }

        /// <summary>
        ///     去除HTML标记
        /// </summary>
        /// <param name="htmlstring"></param>
        /// <returns>已经去除后的文字</returns>
        public static string RemoveHtml(string htmlstring)
        {
            //删除脚本
            htmlstring =
                Regex.Replace(htmlstring, @"<script[^>]*?>.*?</script>",
                              "", RegexOptions.IgnoreCase);
            //删除HTML
            htmlstring = Regex.Replace(htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            htmlstring = htmlstring.Replace("<", "");
            htmlstring = htmlstring.Replace(">", "");
            htmlstring = htmlstring.Replace("\r\n", "");
            return htmlstring;
        }
时间: 2025-01-21 06:49:49

将HtmlTable内容导出到Excel,使用NPOI组件的相关文章

ASP.NET中把Gridview内容导出到Excel示例

第一步:先建立一个基本的aspx页面default.aspx,我们掐头去尾,只来关键的代码:  代码如下 复制代码 <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </div> <br/> <asp:

把指定的DataSet中的内容导出到Excel中

  /// <summary>  /// 把指定的DataSet中的内容导出到Excel中.  /// </summary>  /// <param name="ds">ds参数为DateSet对象</param>  /// <param name="ImpStr">该字符串用来指定一些字段来导出,其使用格式为:aaa|AAA,bbb|BBB   小写字符串为在Excel表中显示该字段的列标题,大写表示字段

紧急求助啊!怎么将动态加载到页面中的内容导出到excel啊??

问题描述 response.addHeader("Content-disposition","attchment;filename=jyt.xls");response.setContentType("application/vnd.ms-excel");//定义输出类型这两个语句只能将网页中静态的内容导出,但是用ajax从数据库取出来的数据不能导出,怎么办呢??求助各路大虾!! 解决方案 解决方案二:不用其他的jar包,行不解决方案三:有人知道

如何将datagridview显示内容导出为excel文件?在另外的机器上使用时有什么注意事项?

问题描述 将dataGridview中显示的数据导出生成EXCEL文件,已经编译成功,但是放到别的机器上使用的时候又不行,提示版本不对,有什么解决方法吗?运行的机器上已经装有excel.源程序如下:///<summary>///zjjzdq.com.cn///</summary>///<paramname="dt"></param>protectedvoidExportExcel(DataTabledt){if(dt==null||dt.

php中将数据库的内容导出到excel

核心代码就是这里了  代码如下 复制代码 header("Content-Type: application/vnd.ms-excel; charset=UTF-8"); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("

ASP.NET的HTMLTable原样导出到Excel

  function PrintTableToExcelEx(objTab) ...{ try ...{ var xls = new ActiveXObject( "Excel.Application" ); } catch(e) ...{ alert( "您必须安装Excel电子表格软件,同时浏览器须使用"ActiveX 控件",您的浏览器须允许执行控件. 请点击[帮助]了解浏览器设置方法!"); return false; } xls.vis

将ListView中的内容导出到Word和Excel(新)

经常看到有网友发帖子询问如何将ListView中的内容导出到Excel或Word文档中,其实在BCB中用OLE技术来操作,并不复杂,大概是有的人懒的写吧,于是ccrun(老妖)花了点时间写了以下两个函数,实现了将本程序中ListView中内容导出到Excel文档和Word文档.看在写代码很辛苦的份上,请在转载时留下出处和原作者信息.Thank了.:D 如果您有好的想法,欢迎来信讨论: info@ccrun.com2005.10.13 v0.2+ 导出表格增加了标题一栏2005.10.12 v0.

把WebForm数据导出到Excel中

excel|web|数据 上午给系统的订单管理部分添加了一个功能,把查询到的订单信息导出到Excel,供管理员分析用.以前写的代码如下: Response.Clear();Response.BufferOutput = true;Response.Charset = "GB2312";Response.AppendHeader("Content-Disposition","attachment;filename = FileName.xls");

实现easyui的datagrid导出为excel的示例代码_jquery

之前有介绍过如何实现easyui里datagrid内容的打印,今天给大家介绍下如何实现datagrid内容导出为excel文件.以下为代码实现: export.js function ChangeToTable(printDatagrid) { var tableString = '<table cellspacing="0" class="pb">'; var frozenColumns = printDatagrid.datagrid("o