NPOI, table string to excel

因为有4000个style的限制。所以加了个class,保存style。。。重复的style不新new,只有是新的style才new一个style. 这样基本不会达到4000个的限制。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace TestNPOI
{
    public class CellStyle
    {
        public CellStyle(HSSFWorkbook workbook)
        {
            Wk = workbook;
            _cStyle = Wk.CreateCellStyle();
            _font = Wk.CreateFont();
        }
        public static HSSFWorkbook Wk { get; set; }
        public short FillForegroundColor { get; set; }
        public short FontColor { get; set; }
        // left align by default.
        public HorizontalAlignment Alignment { get; set; }
        public string Type { get; set; }
        //public string IsFontBold { get; set; }
        //public string HorizontalAlign { get; set; }
        //public string Underscore { get; set; }
        private ICellStyle _cStyle;
        private readonly IFont _font;

        public ICellStyle CStyle
        {
            get
            {
                _cStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
                _cStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
                _cStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
                _cStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
                _cStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.WHITE.index;
                _cStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;
                _cStyle.FillForegroundColor = this.FillForegroundColor;
                if (Type == "header")
                {
                    _font.Boldweight = (short) FontBoldWeight.BOLD;
                    _cStyle.WrapText = false;
                }
                else
                {
                    _font.Boldweight = (short)FontBoldWeight.None;
                }
                _font.FontName = "verdana";                    //

                //_cStyle.WrapText = true;
                _font.Color = this.FontColor;
                _cStyle.SetFont(_font);
                 _cStyle.Alignment = this.Alignment;
                return _cStyle;
            }
            set { this._cStyle = value; }
        }

    }

}

  下面的是把html string输出到ezcel,这个是针对我的table的,其他的自己慢慢改吧。。。。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Chilkat;
using NPOI.HSSF.Record.CF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;

namespace TestNPOI
{
    public class NPOIHelper
    {
        private readonly List<CellStyle>  _userStyleList = new List<CellStyle>();

        /// <summary>
        /// write html xml string to excel using npoi.
        /// </summary>
        /// <param name="sHtml"></param>
        public void WriteHtmlToExcel(string sHtml)//byte[] WriteHtmlToExcel(string sHtml)
        {

            //  the most important thing is to get a xml string...
            // 1. remove tags that are not closed (maybe html, but not xml friendly)
            // 2. remove special string...

            List<string> multiplePatterns = new List<string>
            {
                "title=\".*?\"",
                "onmouseover=\".*?\"",
                "ondblclick=\".*?\"",
                "<br>",
                "<BR>",
                "<img border=0 alt=‘Show Attachment‘ src=‘Images/IconImage.gif‘>",
                " ",
                "<img src=\"Images.*?>",
                "<input .*?>",
                //"<td >.*?<input name=\".*?>.*?</td>"
            };

            sHtml = Regex.Replace(sHtml, string.Join("|", multiplePatterns), string.Empty);

            var doc = XDocument.Parse(sHtml);
            HSSFWorkbook wk = new HSSFWorkbook();
            ISheet sheet = wk.CreateSheet("Report1");

            ICellStyle style = wk.CreateCellStyle();
            // initialize workbook color pallette.
            style.FillForegroundColor = HtmltoColorIndex(wk, "#CCCC99");

            string[] styleall = { "background", "align", "color" }; // "text-dec","wrap"

            // get header tr
            var queryheader = doc.Descendants("tr").Take(1);

            // get header th
            int count = queryheader.Descendants().Count();
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < count; i++)
            {
                ICell cell = row.CreateCell(i);
                XElement xe = queryheader.Descendants().ElementAtOrDefault(i);
                foreach (string s in styleall)
                {
                    GetStyleAll(xe, wk, ref style, s);
                }

                int index = CheckDuplicateUserStyle(style, wk, "header");
                cell.SetCellValue(xe.Value.Trim());
                cell.CellStyle = _userStyleList[index].CStyle;

                sheet.AutoSizeColumn(i);
            }

            for (int i = 0; i < doc.Descendants("tr").Count() - 1; i++)
            {
                // get data style
                var dataleft = doc.Descendants("tr").Skip(i + 1).Take(1);
                IRow newRow = sheet.CreateRow(i + 1);
                var datarow = dataleft.Descendants("td");
                for (int j = 0; j < datarow.Count(); j++)
                {
                    XElement dataxe = datarow.ElementAtOrDefault(j);
                    ICell newCell = newRow.CreateCell(j);

                    foreach (string s in styleall)
                    {
                        GetStyleAll(dataxe, wk, ref style, s);
                    }

                    int index = CheckDuplicateUserStyle(style, wk, "data");
                    newCell.SetCellValue(dataxe.Value.Trim());
                    newCell.CellStyle = _userStyleList[index].CStyle;
                    sheet.AutoSizeColumn(i);
                }
            }

            // download scripts
            using (MemoryStream ms = new MemoryStream())
            {
                wk.Write(ms);
                //// from web.
                //HttpContext.Current.Response.ContentType = "application/octet-stream";
                //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=report.xls");
                //HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                //// from console -> write to file.
                string dt = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
                using (FileStream fs = new FileStream(@"C:\Users\Richard\Documents\tools\TestNPOI\TestNPOI\bin\" + dt + ".xls", FileMode.Create))
                {
                    ms.WriteTo(fs);
                }
                //// from web/ console, attached to email.
                //return ms.ToArray();

            }
        }
        public void ConvertCellStyleToUserStyle(ICellStyle cellStyle, CellStyle userCellStyle, HSSFWorkbook wk)
        {
            userCellStyle.FillForegroundColor = cellStyle.FillBackgroundColor;
            userCellStyle.FontColor = cellStyle.GetFont(wk).Color;
            userCellStyle.Alignment = cellStyle.Alignment;
        }

        public int CheckDuplicateUserStyle(ICellStyle cellStyle, HSSFWorkbook wk, string type)
        {
            int index = _userStyleList.FindIndex(t => t.FontColor == cellStyle.GetFont(wk).Color && t.FillForegroundColor == cellStyle.FillForegroundColor && t.Alignment == cellStyle.Alignment);
            if (index >= 0) return index;
            CellStyle user = new CellStyle(wk)
            {
                FontColor = cellStyle.GetFont(wk).Color,
                FillForegroundColor = cellStyle.FillForegroundColor,
                Alignment = cellStyle.Alignment,
                Type = type
            };
            _userStyleList.Add(user);
            return _userStyleList.Count - 1;
        }

        public void GetStyleAll(XElement xe, HSSFWorkbook wk, ref ICellStyle cellStyle, string itemstyle)
        {
            int pos_start = -1;
            int pos_len = -1;

            switch (itemstyle)
            {
                case "background": // background color <-> foreground color in excel
                    pos_start = 17;
                    pos_len = 7;
                    break;
                case "text-dec": // underline... actually, no need to do this... can use regex... but no time to change the code....
                    pos_start = 16;
                    pos_len = 9;
                    break;
                case "color": // font color
                    pos_start = 6;
                    pos_len = 7; // changeable
                    break;
                case "align": // alignment
                    pos_start = 6;
                    pos_len = 4; // changeable
                    break;
                //case "wrap":
                //    break;
                default:
                    pos_start = 0;
                    pos_len = 0;
                    break;
            }

            if (itemstyle == "align")
            {
                if (xe.Attribute("align") != null)
                {
                    string attr = xe.Attribute("align").Value;
                    if (attr == "left")
                    {
                        cellStyle.Alignment = HorizontalAlignment.LEFT;
                    }
                    else if (attr == "right")
                    {
                        cellStyle.Alignment = HorizontalAlignment.RIGHT;
                    }
                    else
                    {
                        cellStyle.Alignment = HorizontalAlignment.CENTER;
                    }
                }
                else
                    cellStyle.Alignment = HorizontalAlignment.LEFT;
            }
            //else if (itemstyle == "wrap")
            //{
            //    if (xe.Attribute("wrap") != null)
            //    {
            //        string attr = xe.Attribute("white-space").Value;
            //        cellStyle.WrapText = attr == "nowrap;";
            //    }
            //    else
            //    {
            //        cellStyle.WrapText = false;
            //    }
            //}
            else if (itemstyle == "text-dec")
            {
                if (xe.Attribute("style") != null && xe.Attribute("style").Value.Contains(itemstyle))
                {
                    GetBackColor(xe.Attribute("style").Value, wk,ref cellStyle, pos_start, pos_len, itemstyle);
                }
            }
            else if (itemstyle == "color" || itemstyle == "background")
            {
                if (xe.Attribute("style") != null && xe.Attribute("style").Value.Contains(itemstyle))
                {
                    GetBackColor(xe.Attribute("style").Value, wk,ref cellStyle, pos_start, pos_len, itemstyle);
                }
                else
                {
                    if (xe.Parent.Attribute("style") != null && xe.Parent.Attribute("style").Value.Contains(itemstyle))
                    {
                        GetBackColor(xe.Parent.Attribute("style").Value, wk,ref cellStyle, pos_start, pos_len, itemstyle);
                    }
                    else
                    {
                        if (itemstyle == "background")
                            cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.WHITE.index;
                    }
                }
            }

        }

        /// <summary>
        /// need to re-write if have time....
        /// </summary>
        /// <param name="attr"></param>
        /// <param name="wk"></param>
        /// <param name="cellStyle"></param>
        /// <param name="posStart"></param>
        /// <param name="posLen"></param>
        /// <param name="type"></param>
        public void GetBackColor(string attr, HSSFWorkbook wk, ref ICellStyle cellStyle, int posStart, int posLen, string type)
        {
            int posDes = 0;
            short npoicolor = 0;
            posDes = attr.IndexOf(type, StringComparison.Ordinal);

            switch (type)
            {
                case "background":
                    //Regex regbackcol = new Regex("background-color:[\\w]+;");
                    string myBackString = string.Empty;

                    Regex regbackcol = new Regex("background-color:*([^;]+)");

                    Match matchbackcol = regbackcol.Match(attr);
                    if (matchbackcol.Success)
                    {
                        string colstr = matchbackcol.Value;

                        if (colstr.Contains("#"))
                        {
                            myBackString = colstr.Substring(posStart, posLen);
                        }
                        else if (colstr.Contains("rgb"))
                        {
                            string col = colstr.Substring(posStart, colstr.Length - posStart).Trim();
                            string colrgb = col.Substring(4, col.Length - 4);
                            int colr = int.Parse(colrgb.Split(‘,‘)[0]);
                            int colg = int.Parse(colrgb.Split(‘,‘)[1]);
                            int colb = int.Parse(colrgb.Split(‘,‘)[2]);
                            myBackString = String.Format("#{0:X2}{1:X2}{2:X2}", colr, colg, colb);
                        }
                        else
                        {
                            string col = colstr.Substring(posStart, colstr.Length - posStart);
                            Color color = Color.FromName(col);
                            myBackString = String.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
                        }
                        npoicolor = HtmltoColorIndex(wk, myBackString);
                        if (npoicolor != 0)
                        {
                            cellStyle.FillForegroundColor = npoicolor;
                        }
                    }
                    else
                    {
                        cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.WHITE.index;
                    }
                    break;
                case "align":
                    break;
                case "text-dec":
                    IFont fontdec = wk.GetFontAt(0);
                    fontdec.Underline = FontFormatting.U_SINGLE;
                    cellStyle.SetFont(fontdec);
                    break;
                case "color":
                    attr = attr.Replace("-color", "");
                    int posCol = -1;
                    posCol = attr.IndexOf(type);
                    if (posCol >= 0)
                    {
                        if (attr.Contains("#"))
                        {
                            string col = attr.Substring(posDes + posStart, posLen);
                            short index = HtmltoColorIndex(wk, col);
                            IFont font = wk.GetFontAt(0); //////////////////
                            font.Color = index;
                            font.FontName = "verdana";
                            cellStyle.SetFont(font);
                        }
                        else
                        {
                            Regex reg = new Regex("color:[\\w]+");
                            Match match = reg.Match(attr);
                            if (match.Success)
                            {
                                string colstr = match.Value;
                                string col = colstr.Substring(posStart, colstr.Length - posStart);
                                Color color = Color.FromName(col);
                                string myHexString = String.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
                                short index = HtmltoColorIndex(wk, myHexString);
                                IFont font = wk.GetFontAt(0);///////////////
                                font.Color = index;
                                font.FontName = "verdana";
                                cellStyle.SetFont(font);
                            }
                        }
                    }
                    break;
            }
        }

        public short HtmltoColorIndex(HSSFWorkbook book, string htmlcolor)
        {
            short t = 0;
            System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml(htmlcolor);
            HSSFPalette palette = book.GetCustomPalette();

            HSSFColor hssfColor = palette.FindColor(color.R, color.G, color.B);

            if (hssfColor == null)
            {
                if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255)
                {
                    if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 64)
                    {
                        NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE = 64;
                        NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE += 1;
                        hssfColor = palette.AddColor(color.R, color.G, color.B);
                        hssfColor = palette.FindColor(color.R, color.G, color.B);
                    }
                    else
                    {
                        hssfColor = palette.FindSimilarColor(color.R, color.G, color.B);
                    }

                    t = hssfColor.GetIndex();
                }
            }
            else
            {
                t = hssfColor.GetIndex();
            }

            return t;
        }

        public void AttachExcelToEmail(byte[] buff, Email email, string fileName)
        {
            email.AddDataAttachment(fileName, buff);
        }
    }
}

  

时间: 2024-08-03 05:23:51

NPOI, table string to excel的相关文章

运用NPOI,反射导出EXCEL。

首先我用的是MVC,EF框架,保证查询出来的数据结构如以下结构 var data = list.Select(ps => new { SKU = ps.ProductCode, 中文名称 = ps.Product.Name, 所属公司 = ps.Company.CompanyName, }).ToList(); 调用方法: var excelStr = Service.GetExcelOutStr(data); 实现方法: /// <summary> /// 导出数据(李老师) ///

用NPOI从DataBase到Excel &#39;2

NPOI的C# Helper代码2 1 public static MemoryStream ExportXls(DataTable dt) 2 { 3 HSSFWorkbook wk = new HSSFWorkbook(); 4 ISheet sheet = null; 5 6 string sheetName = "Sheet1"; 7 if (!string.IsNullOrEmpty(dt.TableName)) 8 { 9 sheetName = dt.TableName;

将html table 转成 excel

1 package com.sun.office.excel; 2 3 /** 4 * 跨行元素元数据 5 * 6 */ 7 public class CrossRangeCellMeta { 8 9 public CrossRangeCellMeta(int firstRowIndex, int firstColIndex, int rowSpan, int colSpan) { 10 super(); 11 this.firstRowIndex = firstRowIndex; 12 thi

NPOI导出数据到Excel

NPOI导出数据到Excel 前言 Asp.net操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使用NPOI能够帮助开发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等.NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作. 方法 先去官网:http://npoi.codeplex.com/下载需要

npoi实现数据导出Excel

npoi .NET第三方的Office功能组件. 链接地址 http://npoi.codeplex.com/ 引用命名空间 using NPOI.HSSF.UserModel; using NPOI.HPSF; using NPOI.POIFS.FileSystem; using NPOI.SS.UserModel; 功能代码 /// <summary> /// 操作EXCEL导出数据报表的类 /// </summary> public class DataToExcel { /

NPOI使用ShiftRows向excel插入行,并复制原有样式

使用excel模板导出数据时,模板可填充的数据行有限,可通过ShiftRows插入行,如图,在第七行后插入新行,要求新行包含原有样式 插入后 首先添加npoi类库引用 /// <summary> /// NPOI使用ShiftRows向excel插入行,并复制原有样式 /// </summary> /// <param name="file">模板文件,包含物理路径</param> /// <param name="dir

WeihanLi.Npoi 根据模板导出Excel

WeihanLi.Npoi 根据模板导出Excel Intro 原来的导出方式比较适用于比较简单的导出,每一条数据在一行,数据列虽然自定义程度比较高,如果要一条数据对应多行就做不到了,于是就想支持根据模板导出,在 1.8.0 版本中引入了根据模板导出的功能 使用示例 示例模板 模板规划的可以有三种数据: Global:一个是导出的时候可以指定一些参数,作为 Global 参数,默认参数格式使用: $(Global:PropName) 的格式 Header:配置的对应属性的显示名称,默认是属性名称

Qt将table保存为excel(odbc方式)

首先是保存excel的方法,可参照: http://dzmlmszp.blog.163.com/blog/static/179271962014819111812531/ ok,进入正题. 现在我有一个table,如图: 图中的table可以是QTableWidget或QTableView 但是我需要隐藏最后一列,不要让用户看到,则在代码中加入: ui->tableWidget->setColumnCount(3); 运行中效果如下: 现在问题来了,怎样才能将我的table保存为excel?

js导出table中的EXCEL总结

导出EXCEL一般是用PHP做,但是项目中,有时候PHP后端工程师返回的数据不是我们想要的,作为前端开发工程师,把对应的数据编号转换为文字后,展示给用户,但是,需求要把数据同时导出一份EXCEl.无奈之下,我只能用js导出table中的数据了. 导出EXCEl一般是自己人用的,所以用js导出,因为js导出EXCEL一般情况下兼容性不是很好,很多只是兼容IE浏览器,还要设置在工具栏中进行设置才能导出,因为会相对比较烦.下面介绍几种方法: 一.js导出EXCEl带单元格合并[已验证,比较好用] //