示例#1
0
 public GHyperLink(string url, string text, IFont font, int x, int y)
     : base(text, font, m_Visited.Contains(url) ? VisitedHue : RegularHue, m_Visited.Contains(url) ? VisitedHue : RegularHue, x, y, null)
 {
     base.Underline = true;
     this.m_Url = url;
     base.OnClick = new OnClick(this.Button_OnClick);
 }
示例#2
0
 internal RowTextContent(int tableId, ITemplate template,
     PointGeometry pos, IFont font, double height, double width, float rotation)
     : base(pos, font, height, width, rotation)
 {
     m_TableId = tableId;
     m_TemplateId = 0;
 }
示例#3
0
        public GUI(RenderContext rc)
        {
            //Basic Init

            _fontSmall = rc.LoadFont("Assets/Cabin.ttf", 12);
            _fontMedium = rc.LoadFont("Assets/Cabin.ttf", 18);
            _fontBig = rc.LoadFont("Assets/Cabin.ttf", 40);

            _guiHandler = new GUIHandler();
            _guiHandler.AttachToContext(rc);

            //Start Pannel Init
            _guiPanel = new GUIPanel("PhysicsTest", _fontMedium, 10, 10, 330, 250);

            _info1 = new GUIText("Über die Tasten des Nummernblocks  " , _fontMedium, 30, 170, _color2);
            _info2 = new GUIText("(1-4) kann zwischen 4 verschiedenen ", _fontMedium, 30, 190, _color2);
            _info3 = new GUIText("Szenen gewechselt werden", _fontMedium, 30, 210, _color2);
            _fps = new GUIText("FPS", _fontMedium, 30, 55, _color2);
            _numberRb = new GUIText("Rigidbodies: ", _fontMedium, 30, 85, _color2);
            _shapeType = new GUIText("Collision Shapes: ", _fontMedium, 30, 115, _color2);
            _shapes = new GUIText("", _fontMedium, 50, 135, _color2);

            _guiPanel.ChildElements.Add(_info1);
            _guiPanel.ChildElements.Add(_info2);
            _guiPanel.ChildElements.Add(_info3);
            _guiPanel.ChildElements.Add(_fps);
            _guiPanel.ChildElements.Add(_numberRb);
            _guiPanel.ChildElements.Add(_shapeType);
            _guiPanel.ChildElements.Add(_shapes);

            ShowGUI();
        }
示例#4
0
        public DropDownList(AControl parent)
            : base(parent)
        {
            HandlesMouseInput = true;

            m_Font = ServiceRegistry.GetService<IResourceProvider>().GetAsciiFont(1);
        }
 public void SetUp()
 {
     stubSpriteBatch = MockRepository.GenerateStub<ISpriteBatch>();
     stubFont = MockRepository.GenerateStub<IFont>();
     stubConsole = MockRepository.GenerateStub<IConsole<string>>();
     stubConsole.Log = log;
 }
示例#6
0
文件: Text.cs 项目: prime31/Nez
		public Text setFont( IFont font )
		{
			_font = font;
			updateSize();

			return this;
		}
示例#7
0
 public GServerEntry(Server server, IFont font, IHue hue, int x, int y, int width, int selectedBorderColor, int selectedFillColor, float selectedFillAlpha)
     : base(x, y)
 {
     this.m_yBase = y;
     this.m_SelectedBorderColor = selectedBorderColor;
     this.m_SelectedFillColor = selectedFillColor;
     this.m_SelectedFillAlpha = selectedFillAlpha;
     this.m_Server = server;
     this.m_Name = new GLabel(server.Name, font, hue, 4, 4);
     this.m_Name.X -= this.m_Name.Image.xMin;
     base.m_Children.Add(this.m_Name);
     this.m_PercentFull = new GLabel(string.Format("{0}% full", server.PercentFull), font, hue, width - 5, 4);
     this.m_PercentFull.X -= this.m_PercentFull.Image.xMax;
     base.m_Children.Add(this.m_PercentFull);
     int num = (this.m_Name.Image.yMax - this.m_Name.Image.yMin) + 1;
     this.m_Height = num;
     num = (this.m_PercentFull.Image.yMax - this.m_PercentFull.Image.yMin) + 1;
     if (num > this.m_Height)
     {
         this.m_Height = num;
     }
     this.m_Height += 8;
     this.m_Name.Y = ((this.m_Height - ((this.m_Name.Image.yMax - this.m_Name.Image.yMin) + 1)) / 2) - this.m_Name.Image.yMin;
     this.m_PercentFull.Y = ((this.m_Height - ((this.m_PercentFull.Image.yMax - this.m_PercentFull.Image.yMin) + 1)) / 2) - this.m_PercentFull.Image.yMin;
     this.m_Width = width;
 }
示例#8
0
 public GServerList(Server[] servers, int x, int y, int width, int height, int gumpID, IFont font, IHue hue, int selectionBorderColor, int selectionFillColor, int selectionFillAlpha)
     : base(gumpID, width, height, x, y, true)
 {
     this.m_xLast = -2147483648;
     this.m_yLast = -2147483648;
     int offsetX = base.OffsetX;
     int offsetY = base.OffsetY;
     int useWidth = base.UseWidth;
     this.m_Entries = new GServerEntry[servers.Length];
     for (int i = 0; i < servers.Length; i++)
     {
         this.m_Entries[i] = new GServerEntry(servers[i], font, hue, offsetX, offsetY, useWidth, selectionBorderColor, selectionFillColor, ((float) selectionFillAlpha) / 255f);
         offsetY += this.m_Entries[i].Height - 1;
         base.m_Children.Add(this.m_Entries[i]);
     }
     offsetY++;
     offsetY -= base.OffsetY;
     if (offsetY > (base.UseHeight - 2))
     {
         base.m_Children.Add(new GImage(0x101, this.Width - 6, 4));
         base.m_Children.Add(new GImage(0xff, this.Width - 6, this.Height - 0x25));
         for (int j = 0x22; (j + 0x20) < (this.Height - 5); j += 30)
         {
             base.m_Children.Add(new GImage(0x100, this.Width - 6, j));
         }
         base.m_NonRestrictivePicking = true;
         this.m_Slider = new GVSlider(0xfe, this.Width - 5, 0x11, 13, 0xec, 0.0, 0.0, (double) (offsetY - (base.UseHeight - 2)), 1.0);
         this.m_Slider.OnValueChange = new OnValueChange(this.OnScroll);
         this.m_Slider.ScrollOffset = 20.0;
         base.m_Children.Add(this.m_Slider);
         base.m_Children.Add(new GHotspot(this.Width - 6, 4, 15, this.Height - 9, this.m_Slider));
     }
 }
示例#9
0
 public GSpellName(int SpellID, string Name, IFont Font, IHue HRegular, IHue HOver, int X, int Y)
     : base(Name, Font, HRegular, HOver, X, Y, null)
 {
     this.m_SpellID = SpellID;
     base.m_CanDrag = true;
     base.m_QuickDrag = false;
 }
示例#10
0
        // is called on startup
        public override void Init()
        {
            //TestSerialize();
            //TestDeserialize();

            // GUI initialization
            _zVal = 500;
            _guiHandler = new GUIHandler();
            _guiHandler.AttachToContext(RC);

            _guiFuseeLink = new GUIButton(6, 6, 157, 87);
            _guiFuseeLink.ButtonColor = new float4(0, 0, 0, 0);
            _guiFuseeLink.BorderColor = new float4(0, 0.6f, 0.2f, 1);
            _guiFuseeLink.BorderWidth = 0;
            _guiFuseeLink.OnGUIButtonDown += _guiFuseeLink_OnGUIButtonDown;
            _guiFuseeLink.OnGUIButtonEnter += _guiFuseeLink_OnGUIButtonEnter;
            _guiFuseeLink.OnGUIButtonLeave += _guiFuseeLink_OnGUIButtonLeave;
            _guiHandler.Add(_guiFuseeLink);

            _guiFuseeLogo = new GUIImage("Assets/FuseeLogo150.png", 10, 10, -5, 150, 80);
            _guiHandler.Add(_guiFuseeLogo);

            _guiLatoBlack = RC.LoadFont("Assets/Lato-Black.ttf", 14);
            _guiSubText = new GUIText("FUSEE 3D Scene Viewer", _guiLatoBlack, 100, 100);
            _guiSubText.TextColor = new float4(0.05f, 0.25f, 0.15f, 0.8f);
            _guiHandler.Add(_guiSubText);

            // Scene loading
            SceneContainer scene;
            var ser = new Serializer();
            using (var file = File.OpenRead(@"Assets/Model.fus"))
            {
                scene = ser.Deserialize(file, null, typeof(SceneContainer)) as SceneContainer;
            }
            _sr = new SceneRenderer(scene, "Assets");
            AdjustModelScaleOffset();
            _guiSubText.Text = "FUSEE 3D Scene";
            if (scene.Header.CreatedBy != null || scene.Header.CreationDate != null)
            {
                _guiSubText.Text += " created";
                if (scene.Header.CreatedBy != null)
                {
                    _guiSubText.Text += " by " + scene.Header.CreatedBy;
                }
                if (scene.Header.CreationDate != null)
                {
                    _guiSubText.Text += " on " + scene.Header.CreationDate;
                }
            }

            _subtextWidth = GUIText.GetTextWidth(_guiSubText.Text, _guiLatoBlack);
            _subtextHeight = GUIText.GetTextHeight(_guiSubText.Text, _guiLatoBlack);

            _sColor = MoreShaders.GetDiffuseColorShader(RC);
            RC.SetShader(_sColor);
            _colorParam = _sColor.GetShaderParam("color");
            RC.SetShaderParam(_colorParam, new float4(1, 1, 1, 1));
            RC.ClearColor = new float4(1, 1, 1, 1);
        }
示例#11
0
 public TextPainter(Plotter plotter, IFont font, int sizeX, int sizeY, int spaceX)
 {
     this.plotter = plotter;
     this.font = font;
     this.sizeX = sizeX;
     this.sizeY = sizeY;
     this.spaceX = spaceX;
 }
示例#12
0
        public InputOverlayView(InputLine inputLine, Rectangle inputWindow, IFont font)
        {
            _inputLine = inputLine;
            this.Window = inputWindow;
            _font = font;

            this.BackgroundColor = OverlaySetView.BACKGROUND_COLOR;
        }
示例#13
0
        public DropDownList(AControl owner)
            : base(owner)
        {
            HandlesMouseInput = true;

            m_UserInterface = ServiceRegistry.GetService<UserInterfaceService>();
            m_Font = ServiceRegistry.GetService<IUIResourceProvider>().GetAsciiFont(1);
        }
示例#14
0
 /// <summary>
 /// Creates a new <c>TextGeometry</c>
 /// </summary>
 /// <param name="pos">Position of the text's reference point (always the top left corner of the string).</param>
 /// <param name="font">The text style (defines the type-face and the height of the text).</param>
 /// <param name="height">The height of the text, in meters on the ground.</param>
 /// <param name="width">The total width of the text, in meters on the ground.</param>
 /// <param name="rotation">Clockwise rotation from horizontal</param>
 protected TextGeometry(PointGeometry pos, IFont font, double height, double width, float rotation)
 {
     m_Font = font;
     m_Position = pos;
     m_Height = (float)height;
     m_Width = (float)width;
     m_Rotation = new RadianValue((double)rotation);
 }
示例#15
0
 public GListBox(IFont Font, IHue HRegular, IHue HOver, int BackID, int X, int Y, int Width, int Height, bool HasBorder)
     : base(BackID, Width, Height, X, Y, HasBorder)
 {
     this.m_Font = Font;
     this.m_HRegular = HRegular;
     this.m_HOver = HOver;
     this.m_ItemCount = base.UseHeight / 0x12;
 }
示例#16
0
 public ConsoleOverlaySetView(IOverlayView inputView, IOverlayView commandConsoleView, IOverlayView messageConsoleView, IOverlayView possibleCommandsView, ISpriteBatch spriteBatch, ITexture texture, IFont font)
     : base(spriteBatch, texture, font)
 {
     _overlays.Add(inputView);
     _overlays.Add(commandConsoleView);
     _overlays.Add(messageConsoleView);
     _overlays.Add(possibleCommandsView);
 }
示例#17
0
 private GDynamicMessage(bool unremovable, IMessageOwner owner, string text, IFont font, IHue hue, float duration)
     : base(text, font, hue, Hues.Load(0x35), 0, 0, null)
 {
     this.m_Unremovable = unremovable;
     base.m_OverridesCursor = false;
     this.m_Owner = owner;
     this.m_SolidDuration = duration;
     this.m_Dispose = new TimeSync((double) (this.m_SolidDuration + 1f));
 }
示例#18
0
 public RichLabel()
 {
     text = new List<RichLabelString>();
     Fonts = new List<IFont>();
     Fonts.Add(GUI.Instance.Skin.Font);
     activeFont = Fonts[0];
     Colors = new List<Color>();
     Colors.Add(Color.Black);
     activeColor = Colors[0];
 }
示例#19
0
 public GSystemMessage(string text, IFont font, IHue hue, float duration)
     : base(text, font, hue, 0, 0)
 {
     base.m_OverridesCursor = false;
     this.m_SolidDuration = duration;
     this.m_Dispose = new TimeSync((double) (this.m_SolidDuration + 1f));
     this.m_UpdateTime = DateTime.Now;
     this.m_DupeCount = 1;
     this.m_OrigText = text;
 }
示例#20
0
 public GWrappedLabel(string text, IFont font, IHue hue, int x, int y, int width)
     : base(x, y)
 {
     this.m_WrapWidth = width;
     base.m_Text = text;
     base.m_Font = font;
     base.m_Hue = hue;
     base.m_ITranslucent = true;
     this.Refresh();
 }
        /// <summary>
        ///     Gets the height of a text written in a specific font.
        /// </summary>
        /// <param name="text">The text's string.</param>
        /// <param name="font">The text's font.</param>
        /// <returns>The height of the text.</returns>
        public static float GetTextHeight(string text, IFont font)
        {
            var maxH = 0.0f;

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var letter in text)
                maxH = System.Math.Max(maxH, font.CharInfo[letter].BitmapH);

            return maxH;
        }
示例#22
0
文件: Text.cs 项目: prime31/Nez
		public Text( IFont font, string text, Vector2 localOffset, Color color )
		{
			_font = font;
			_text = text;
			_localOffset = localOffset;
			this.color = color;
			_horizontalAlign = HorizontalAlign.Left;
			_verticalAlign = VerticalAlign.Top;

			updateSize();
		}
示例#23
0
        public GuiRenderer(GraphicsContext graphicsContext, IColourScheme colourScheme)
        {
            ColourScheme = colourScheme;
            _graphicsContext = graphicsContext;
            _primitiveRenderer = _graphicsContext.CreateVertexRenderer<TransformedColouredVertex>(18);
            _textureRenderer = _graphicsContext.CreateVertexRenderer<TransformedColouredTexturedVertex>(9*2*3);

            _font = graphicsContext.GetFont(DefaultFontName, DefautltFontSize, Weight.Bold);

            PrecacheTextures(colourScheme);
        }
示例#24
0
 public GAttributeCurMax(int x, int y, int w, int h, int c, int m, IFont font, IHue hue)
     : base(x, y, w, h)
 {
     this.m_Current = c;
     this.m_Maximum = m;
     this.m_GCurrent = new GWrappedLabel(this.m_Current.ToString(), font, hue, 0, 0, w * 2);
     this.m_GMaximum = new GWrappedLabel(this.m_Maximum.ToString(), font, hue, 0, 11, w * 2);
     base.m_Children.Add(this.m_GCurrent);
     base.m_Children.Add(this.m_GMaximum);
     this.Update();
 }
 public void SetUp()
 {
     stubInputView = MockRepository.GenerateStub<IOverlayView>();
     stubCommandConsoleView = MockRepository.GenerateStub<IOverlayView>();
     stubMessageConsoleView = MockRepository.GenerateStub<IOverlayView>();
     stubPossibleCommandsView = MockRepository.GenerateStub<IOverlayView>();
     stubSpriteBatch = MockRepository.GenerateStub<ISpriteBatch>();
     stubTexture = MockRepository.GenerateStub<ITexture>();
     stubFont = MockRepository.GenerateStub<IFont>();
     hudView = new ConsoleOverlaySetView(stubInputView, stubCommandConsoleView, stubMessageConsoleView, stubPossibleCommandsView, stubSpriteBatch, stubTexture, stubFont);
 }
示例#26
0
        public ScoreOverlayView(IPlayerList playerList, Rectangle scoreWindow, IFont font)
        {
            _playerList = playerList;
            this.Window = scoreWindow;
            _font = font;

            this.BackgroundColor = OverlaySetView.BACKGROUND_COLOR;

            SCORE_OFFSET = new Vector2(scoreWindow.Width / 2, 0);
            DEATHS_OFFSET = new Vector2(scoreWindow.Width * ((float)2 / 3), 0);
        }
示例#27
0
 private static void CreateStyle(XSSFWorkbook workbook)
 {
     //获取字体
     _normalFont = GetFontStyle(workbook, "宋体", null, 14);
     _scoreFont = GetFontStyle(workbook, "宋体", _scoreColor, 24);
     _winRateFont = GetFontStyle(workbook, "宋体", _winRateColor, 14);
     //获取样式
     _normalLeftCellStyle = GetCellStyle(workbook, _normalFont, null, FillPattern.NoFill, null, HorizontalAlignment.Left, VerticalAlignment.Center);
     _normalCenterCellStyle = GetCellStyle(workbook, _normalFont, null, FillPattern.NoFill, null, HorizontalAlignment.Center, VerticalAlignment.Center);
     _aquaCellStyle = GetCellStyle(workbook, _normalFont, _bgColor1, FillPattern.SolidForeground, null, HorizontalAlignment.Left, VerticalAlignment.Center);
     _greycellStyle = GetCellStyle(workbook, _normalFont, _bgColor2, FillPattern.SolidForeground, null, HorizontalAlignment.Center, VerticalAlignment.Center);
 }
示例#28
0
 public GTextButton(string text, IFont font, IHue defaultHue, IHue focusHue, int x, int y, Client.OnClick onClick)
     : base(x, y)
 {
     this.m_CanHitTest = true;
     this.m_Hues = new IHue[] { defaultHue, focusHue };
     this.m_OnClick = onClick;
     base.m_Text = text;
     base.m_Font = font;
     base.m_Hue = defaultHue;
     base.m_ITranslucent = true;
     this.Refresh();
 }
示例#29
0
 public GLabel(string Text, IFont Font, IHue Hue, int X, int Y)
     : base(X, Y)
 {
     this.m_Invalidated = true;
     this.m_Text = "";
     this.m_fAlpha = 1f;
     this.m_Text = Text;
     this.m_Font = Font;
     this.m_Hue = Hue;
     base.m_ITranslucent = true;
     this.Refresh();
 }
示例#30
0
 public StyleState(StyleState parent)
 {
     m_IsUnderlined = parent.m_IsUnderlined;
     IsBold = parent.IsBold;
     IsItalic = parent.IsItalic;
     IsOutlined = parent.IsOutlined;
     Font = parent.Font;
     Color = parent.Color;
     ColorHue = parent.ColorHue;
     ActiveColorHue = parent.ActiveColorHue;
     HoverColorHue = parent.HoverColorHue;
     HREF = parent.HREF;
 }
示例#31
0
        private static ICellStyle GetCellStyle(IWorkbook wb, XlsStyle str, Font headFont = null, Font contentFont = null, Font titleFont = null)
        {
            ICellStyle cellStyle = wb.CreateCellStyle();
            //定义几种字体
            //也可以一种字体,写一些公共属性,然后在下面需要时加特殊的

            IFont font = wb.CreateFont();

            font.FontName           = "微软雅黑";
            font.FontHeightInPoints = 10;

            if (contentFont != null)
            {
                font.FontName = contentFont.Name;
                if (contentFont.Bold)
                {
                    font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
                }
                font.FontHeightInPoints = (short)contentFont.SizeInPoints;
                font.IsItalic           = contentFont.Italic;
                font.IsStrikeout        = contentFont.Strikeout;
                font.Underline          = (byte)(contentFont.Underline ? 1 : 0);
            }

            IFont linkAddresFont = wb.CreateFont();

            linkAddresFont.Color    = HSSFColor.OLIVE_GREEN.BLUE.index;
            linkAddresFont.IsItalic = true;//下划线
            linkAddresFont.FontName = "微软雅黑";

            //边框
            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
            cellStyle.BorderLeft   = NPOI.SS.UserModel.BorderStyle.THIN;
            cellStyle.BorderRight  = NPOI.SS.UserModel.BorderStyle.THIN;
            cellStyle.BorderTop    = NPOI.SS.UserModel.BorderStyle.THIN;
            //边框颜色
            //cellStyle.BottomBorderColor = HSSFColor.OLIVE_GREEN.BLUE.index;
            //cellStyle.TopBorderColor = HSSFColor.OLIVE_GREEN.BLUE.index;
            //背景图形,我没有用到过。感觉很丑
            //cellStyle.FillBackgroundColor = HSSFColor.OLIVE_GREEN.BLUE.index;
            //cellStyle.FillForegroundColor = HSSFColor.OLIVE_GREEN.BLUE.index;
            cellStyle.FillForegroundColor = HSSFColor.WHITE.index;
            // cellStyle.FillPattern = FillPatternType.NO_FILL;
            cellStyle.FillBackgroundColor = HSSFColor.BLUE.index;
            //水平对齐
            cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;
            //垂直对齐
            cellStyle.VerticalAlignment = VerticalAlignment.CENTER;
            //自动换行
            cellStyle.WrapText = true;
            //缩进;当设置为1时,前面留的空白太大了。希旺官网改进。或者是我设置的不对
            cellStyle.Indention = 0;
            //上面基本都是设共公的设置
            //下面列出了常用的字段类型
            switch (str)
            {
            case XlsStyle.Title:
                cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
                if (titleFont != null)
                {
                    font.FontName = titleFont.Name;
                    if (titleFont.Bold)
                    {
                        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
                    }
                    font.FontHeightInPoints = (short)titleFont.SizeInPoints;
                    font.IsItalic           = titleFont.Italic;
                    font.IsStrikeout        = titleFont.Strikeout;
                    font.Underline          = (byte)(titleFont.Underline ? 1 : 0);
                }
                cellStyle.BorderTop    = NPOI.SS.UserModel.BorderStyle.NONE;
                cellStyle.BorderLeft   = NPOI.SS.UserModel.BorderStyle.NONE;
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.NONE;
                cellStyle.BorderRight  = NPOI.SS.UserModel.BorderStyle.NONE;
                cellStyle.SetFont(font);
                break;

            case XlsStyle.Header:
                // cellStyle.FillPattern = FillPatternType.LEAST_DOTS;
                cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
                if (headFont != null)
                {
                    font.FontName = headFont.Name;
                    if (headFont.Bold)
                    {
                        font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
                    }
                    font.FontHeightInPoints = (short)headFont.SizeInPoints;
                    font.IsItalic           = headFont.Italic;
                    font.IsStrikeout        = headFont.Strikeout;
                    font.Underline          = (byte)(headFont.Underline ? 1 : 0);
                }
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.MEDIUM;
                cellStyle.BorderLeft   = NPOI.SS.UserModel.BorderStyle.MEDIUM;
                cellStyle.BorderRight  = NPOI.SS.UserModel.BorderStyle.MEDIUM;
                cellStyle.BorderTop    = NPOI.SS.UserModel.BorderStyle.MEDIUM;
                cellStyle.SetFont(font);
                break;

            case XlsStyle.Bottom:
                cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.RIGHT;
                //if (bottomFont != null)
                //{
                //    font.FontName = bottomFont.Name;
                //    if (bottomFont.Bold) font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
                //    font.FontHeightInPoints = (short)bottomFont.SizeInPoints;
                //    font.IsItalic = bottomFont.Italic;
                //    font.IsStrikeout = bottomFont.Strikeout;
                //    font.Underline = (byte)(bottomFont.Underline ? 1 : 0);
                //}
                cellStyle.BorderTop    = NPOI.SS.UserModel.BorderStyle.NONE;
                cellStyle.BorderLeft   = NPOI.SS.UserModel.BorderStyle.NONE;
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.NONE;
                cellStyle.BorderRight  = NPOI.SS.UserModel.BorderStyle.NONE;
                cellStyle.SetFont(font);
                break;

            case XlsStyle.Serial:
                cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
                font.Boldweight     = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
                cellStyle.SetFont(font);
                break;

            case XlsStyle.Time:
                IDataFormat dataStyle = wb.CreateDataFormat();
                cellStyle.DataFormat = dataStyle.GetFormat("yyyy-mm-dd");
                cellStyle.SetFont(font);
                break;

            case XlsStyle.Number:
                cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
                cellStyle.Alignment  = NPOI.SS.UserModel.HorizontalAlignment.GENERAL;
                cellStyle.SetFont(font);
                break;

            case XlsStyle.Money:
                IDataFormat format = wb.CreateDataFormat();
                cellStyle.DataFormat = format.GetFormat("¥#,##0");
                cellStyle.Alignment  = NPOI.SS.UserModel.HorizontalAlignment.GENERAL;
                cellStyle.SetFont(font);
                break;

            case XlsStyle.Url:
                linkAddresFont.Underline = 1;
                cellStyle.SetFont(linkAddresFont);
                break;

            case XlsStyle.Percent:
                cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00%");
                cellStyle.Alignment  = NPOI.SS.UserModel.HorizontalAlignment.GENERAL;
                cellStyle.SetFont(font);
                break;

            case XlsStyle.Chupper:
                IDataFormat format1 = wb.CreateDataFormat();
                cellStyle.DataFormat = format1.GetFormat("[DbNum2][$-804]0");
                cellStyle.SetFont(font);
                break;

            case XlsStyle.Tnumber:
                cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00E+00");
                cellStyle.SetFont(font);
                break;

            case XlsStyle.Default:
                cellStyle.SetFont(font);
                break;
            }
            return(cellStyle);
        }
示例#32
0
        /**
         * create a library of cell styles
         */
        private static Dictionary <String, ICellStyle> createStyles(IWorkbook wb)
        {
            Dictionary <String, ICellStyle> styles = new Dictionary <String, ICellStyle>();
            IDataFormat df = wb.CreateDataFormat();

            ICellStyle style;
            IFont      headerFont = wb.CreateFont();

            headerFont.Boldweight = (short)(FontBoldWeight.BOLD);
            style                     = CreateBorderedStyle(wb);
            style.Alignment           = HorizontalAlignment.CENTER;
            style.FillForegroundColor = (IndexedColors.LIGHT_CORNFLOWER_BLUE.Index);
            style.FillPattern         = FillPatternType.SOLID_FOREGROUND;
            style.SetFont(headerFont);
            styles.Add("header", style);

            style                     = CreateBorderedStyle(wb);
            style.Alignment           = HorizontalAlignment.CENTER;
            style.FillForegroundColor = (IndexedColors.LIGHT_CORNFLOWER_BLUE.Index);
            style.FillPattern         = FillPatternType.SOLID_FOREGROUND;
            style.SetFont(headerFont);
            style.DataFormat = (df.GetFormat("d-mmm"));
            styles.Add("header_date", style);

            IFont font1 = wb.CreateFont();

            font1.Boldweight = (short)(FontBoldWeight.BOLD);
            style            = CreateBorderedStyle(wb);
            style.Alignment  = HorizontalAlignment.CENTER;
            style.SetFont(font1);
            styles.Add("cell_b", style);

            style           = CreateBorderedStyle(wb);
            style.Alignment = HorizontalAlignment.CENTER;
            style.SetFont(font1);
            styles.Add("cell_b_centered", style);

            style           = CreateBorderedStyle(wb);
            style.Alignment = HorizontalAlignment.CENTER;
            style.SetFont(font1);
            style.DataFormat = (df.GetFormat("d-mmm"));
            styles.Add("cell_b_date", style);

            style           = CreateBorderedStyle(wb);
            style.Alignment = HorizontalAlignment.CENTER;
            style.SetFont(font1);
            style.FillForegroundColor = (IndexedColors.GREY_25_PERCENT.Index);
            style.FillPattern         = FillPatternType.SOLID_FOREGROUND;
            style.DataFormat          = (df.GetFormat("d-mmm"));
            styles.Add("cell_g", style);

            IFont font2 = wb.CreateFont();

            font2.Color      = (IndexedColors.BLUE.Index);
            font2.Boldweight = (short)(FontBoldWeight.BOLD);
            style            = CreateBorderedStyle(wb);
            style.Alignment  = HorizontalAlignment.CENTER;
            style.SetFont(font2);
            styles.Add("cell_bb", style);

            style           = CreateBorderedStyle(wb);
            style.Alignment = HorizontalAlignment.CENTER;
            style.SetFont(font1);
            style.FillForegroundColor = (IndexedColors.GREY_25_PERCENT.Index);
            style.FillPattern         = FillPatternType.SOLID_FOREGROUND;
            style.DataFormat          = (df.GetFormat("d-mmm"));
            styles.Add("cell_bg", style);

            IFont font3 = wb.CreateFont();

            font3.FontHeightInPoints = ((short)14);
            font3.Color      = (IndexedColors.DARK_BLUE.Index);
            font3.Boldweight = (short)(FontBoldWeight.BOLD);
            style            = CreateBorderedStyle(wb);
            style.Alignment  = HorizontalAlignment.CENTER;
            style.SetFont(font3);
            style.WrapText = (true);
            styles.Add("cell_h", style);

            style           = CreateBorderedStyle(wb);
            style.Alignment = HorizontalAlignment.CENTER;
            style.WrapText  = (true);
            styles.Add("cell_normal", style);

            style           = CreateBorderedStyle(wb);
            style.Alignment = HorizontalAlignment.CENTER;
            style.WrapText  = (true);
            styles.Add("cell_normal_centered", style);

            style            = CreateBorderedStyle(wb);
            style.Alignment  = HorizontalAlignment.CENTER;
            style.WrapText   = (true);
            style.DataFormat = (df.GetFormat("d-mmm"));
            styles.Add("cell_normal_date", style);

            style           = CreateBorderedStyle(wb);
            style.Alignment = HorizontalAlignment.CENTER;
            style.Indention = ((short)1);
            style.WrapText  = (true);
            styles.Add("cell_indented", style);

            style = CreateBorderedStyle(wb);
            style.FillForegroundColor = (IndexedColors.BLUE.Index);
            style.FillPattern         = FillPatternType.SOLID_FOREGROUND;
            styles.Add("cell_blue", style);

            return(styles);
        }
示例#33
0
        private void ExportToExcel(string path)
        {
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                ISheet       sheet    = workbook.CreateSheet("系统日志报表");

                //第一行样式及内容
                IRow row = sheet.CreateRow(0);

                row.HeightInPoints = 40;

                ICell cell = row.CreateCell(0, CellType.String);

                cell.SetCellValue("系统日志报表");

                ICellStyle style = workbook.CreateCellStyle();

                IFont font = workbook.CreateFont();

                font.FontHeightInPoints = 18;

                font.FontName = "宋体";

                font.Boldweight = 800;

                style.SetFont(font);

                style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;

                style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Justify;

                cell.CellStyle = style;

                sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 5));

                //设置列宽
                sheet.SetColumnWidth(0, 12 * 256);
                for (int i = 1; i < 6; i++)
                {
                    sheet.SetColumnWidth(i, 20 * 256);
                }

                ICellStyle style2 = workbook.CreateCellStyle();
                style2.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Left;
                style2.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Justify;
                IFont font2 = workbook.CreateFont();
                font2.FontHeightInPoints = 12;
                font2.FontName           = "宋体";
                style2.SetFont(font2);

                //第二行(表头)
                IRow row2 = sheet.CreateRow(1);

                ICell headCell1 = row2.CreateCell(0, CellType.String);
                headCell1.CellStyle = style2;
                headCell1.SetCellValue("流水号");

                ICell headCell2 = row2.CreateCell(1, CellType.String);
                headCell2.CellStyle = style2;
                headCell2.SetCellValue("菜单名称");

                ICell headCell3 = row2.CreateCell(2, CellType.String);
                headCell3.CellStyle = style2;
                headCell3.SetCellValue("操作类型");

                ICell headCell4 = row2.CreateCell(3, CellType.String);
                headCell4.CellStyle = style2;
                headCell4.SetCellValue("操作时间");

                ICell headCell5 = row2.CreateCell(4, CellType.String);
                headCell5.SetCellValue("操作内容");
                headCell5.CellStyle = style2;

                ICell headCell6 = row2.CreateCell(5, CellType.String);
                headCell6.SetCellValue("操作用户");
                headCell6.CellStyle = style2;


                //填充数据到单元格
                for (int i = 0; i < currentTable.Rows.Count; i++)
                {
                    IRow  irow  = sheet.CreateRow(i + 2);
                    ICell cell1 = irow.CreateCell(0, CellType.Numeric);
                    cell1.SetCellValue(Convert.ToInt32(currentTable.Rows[i]["NUMB_SYSLOG"]));

                    ICell cell2 = irow.CreateCell(1, CellType.String);
                    cell2.SetCellValue(currentTable.Rows[i]["FK_NAME_MENU"].ToString());

                    ICell cell3 = irow.CreateCell(2, CellType.String);
                    cell3.SetCellValue(currentTable.Rows[i]["FLAG_LOGSORT"].ToString());

                    ICell cell4 = irow.CreateCell(3, CellType.String);
                    cell4.SetCellValue((Convert.ToDateTime(currentTable.Rows[i]["INFO_DATE"])).ToString("yyyy-MM-dd HH:mm:ss"));

                    ICell cell5 = irow.CreateCell(4, CellType.String);
                    cell5.SetCellValue(currentTable.Rows[i]["INFO_CONT"].ToString());

                    ICell cell6 = irow.CreateCell(5, CellType.String);
                    cell6.SetCellValue(currentTable.Rows[i]["FK_NAME_USER"].ToString());
                }

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

                workbook.Write(file);

                file.Close();

                this.Dispatcher.Invoke(new Action(() =>
                {
                    Toolkit.MessageBox.Show("导出成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }));
            }
            catch (Exception)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    Toolkit.MessageBox.Show("导出失败!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }));
            }
        }
示例#34
0
 /// <summary>
 /// 设置粗体
 /// </summary>
 /// <param name="font">字体</param>
 /// <param name="boldweight">粗体大小</param>
 /// <returns></returns>
 public static IFont SetBoldweight(this IFont font, short boldweight)
 {
     font.Boldweight = boldweight;
     return(font);
 }
示例#35
0
 /// <summary>
 /// 设置字体大小
 /// </summary>
 /// <param name="font">字体</param>
 /// <param name="fontSize">字体大小</param>
 /// <returns></returns>
 public static IFont SetFontHeightInPoints(this IFont font, short fontSize)
 {
     font.FontHeightInPoints = fontSize;
     return(font);
 }
示例#36
0
        /// <summary>
        /// DataTable 导出到 Excel 的 MemoryStream
        /// </summary>
        /// <param name="dtSource">源 DataTable</param>
        /// <param name="strHeaderText">表头文本 空值未不要表头标题</param>
        /// <returns></returns>
        public static MemoryStream ExportExcel(DataTable dtSource, string strHeaderText)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet       sheet    = workbook.CreateSheet();

            #region 文件属性
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "yuebon.com";
            workbook.DocumentSummaryInformation = dsi;
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Author                   = "yuebon.com";
            si.ApplicationName          = "yuebon.com";
            si.LastAuthor               = "yuebon.com";
            si.Comments                 = "";
            si.Title                    = "";
            si.Subject                  = "";
            si.CreateDateTime           = DateTime.Now;
            workbook.SummaryInformation = si;
            #endregion
            ICellStyle  dateStyle = workbook.CreateCellStyle();
            IDataFormat format    = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
            int[] arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding("gb2312").GetBytes(item.ColumnName.ToString()).Length;
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    int intTemp = Encoding.GetEncoding("gb2312").GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }
            int rowIndex = 0;
            int intTop   = 0;
            foreach (DataRow row in dtSource.Rows)
            {
                #region 新建表、填充表头、填充列头,样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet = workbook.CreateSheet();
                    }
                    intTop = 0;
                    #region 表头及样式
                    {
                        if (strHeaderText.Length > 0)
                        {
                            IRow headerRow = sheet.CreateRow(intTop);
                            intTop += 1;
                            headerRow.HeightInPoints = 25;
                            headerRow.CreateCell(0).SetCellValue(strHeaderText);
                            ICellStyle headStyle = workbook.CreateCellStyle();
                            headStyle.Alignment = HorizontalAlignment.Center;
                            IFont font = workbook.CreateFont();
                            font.FontHeightInPoints = 20;
                            font.Boldweight         = 700;
                            headStyle.SetFont(font);
                            headerRow.GetCell(0).CellStyle = headStyle;
                            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
                        }
                    }
                    #endregion
                    #region  列头及样式
                    {
                        IRow headerRow = sheet.CreateRow(intTop);
                        intTop += 1;
                        ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;
                        IFont font = workbook.CreateFont();
                        font.Boldweight = 700;
                        headStyle.SetFont(font);
                        foreach (DataColumn column in dtSource.Columns)
                        {
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
                            //设置列宽
                            sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                        }
                    }
                    #endregion
                    rowIndex = intTop;
                }
                #endregion
                #region 填充内容
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    ICell  newCell = dataRow.CreateCell(column.Ordinal);
                    string drValue = row[column].ToString();
                    switch (column.DataType.ToString())
                    {
                    case "System.String":    //字符串类型
                        newCell.SetCellValue(drValue);
                        break;

                    case "System.DateTime":    //日期类型
                        DateTime dateV;
                        DateTime.TryParse(drValue, out dateV);
                        newCell.SetCellValue(dateV);
                        newCell.CellStyle = dateStyle;    //格式化显示
                        break;

                    case "System.Boolean":    //布尔型
                        bool boolV = false;
                        bool.TryParse(drValue, out boolV);
                        newCell.SetCellValue(boolV);
                        break;

                    case "System.Int16":
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Byte":
                        int intV = 0;
                        int.TryParse(drValue, out intV);
                        newCell.SetCellValue(intV);
                        break;

                    case "System.Decimal":
                    case "System.Double":
                        double doubV = 0;
                        double.TryParse(drValue, out doubV);
                        newCell.SetCellValue(doubV);
                        break;

                    case "System.DBNull":    //空值处理
                        newCell.SetCellValue("");
                        break;

                    default:
                        newCell.SetCellValue("");
                        break;
                    }
                }
                #endregion
                rowIndex++;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return(ms);
            }
        }
示例#37
0
        private MemoryStream ListToStream <T>(IList <T> list, IDictionary <string, string> propertyNameList, string title)
        {
            //创建内存流
            using (MemoryStream ms = new MemoryStream())
            {
                //将控制excel表头的参数写入到一个临时集合
                //List<IDictionary<string, string>> propertyNameList = new List<IDictionary<string, string>>();
                //if (propertyName != null)
                //{
                //    propertyNameList.AddRange(propertyName);
                //}

                //创建NOPI对象
                IWorkbook workbook = new HSSFWorkbook();
                ISheet    sheet    = workbook.CreateSheet();
                //表头的行号  如果有标题就是1 没有标题就是0
                int headerRowNum = 0;
                if (!string.IsNullOrEmpty(title))
                {
                    headerRowNum = 1;
                    IRow titleRow = sheet.CreateRow(0);
                    titleRow.Height = 999;

                    ICell titleCell = titleRow.CreateCell(0);
                    titleCell.SetCellValue(title);
                    ICellStyle cellStyle = workbook.CreateCellStyle();
                    //设置字体
                    IFont font = workbook.CreateFont();
                    font.FontHeightInPoints = 18;
                    font.FontName           = "微软雅黑";
                    cellStyle.SetFont(font);
                    //对齐方式
                    cellStyle.Alignment = HorizontalAlignment.Center;
                    titleCell.CellStyle = cellStyle;
                }
                IRow headerRow = sheet.CreateRow(headerRowNum);
                if (list.Count <= 0)
                {
                    return(null);
                }
                //通过反射得到对象的属性集合
                PropertyInfo[] propertys = list[0].GetType().GetProperties();

                //遍历属性集合生成excel的表头标题
                int cellIndex = 0;
                if (propertyNameList == null || propertyNameList.Count == 0)
                {
                    //如果没有传入自定义的导出表头
                    for (int i = 0; i < propertys.Count(); i++)
                    {
                        headerRow.CreateCell(i).SetCellValue(propertys[i].Name);
                    }
                }
                else
                {
                    //用户自定义的
                    foreach (KeyValuePair <string, string> item in propertyNameList)
                    {
                        for (int i = 0; i < propertys.Count(); i++)
                        {
                            if (propertys[i].Name.Equals(item.Key))
                            {
                                headerRow.CreateCell(cellIndex).SetCellValue(item.Value);
                                cellIndex++;
                                break;
                            }
                        }
                    }
                }
                #region  面的方式可以根据传入的列的顺序导入
                //for (int i = 0; i < propertys.Count(); i++)
                //{
                //    //判断excel表头是否是用户定义
                //    if (propertyNameList.Count == 0)
                //    {
                //        headerRow.CreateCell(i).SetCellValue(propertys[i].Name);
                //    }
                //    else
                //    {
                //        foreach (KeyValuePair<string, string> item in propertyNameList)
                //        {
                //            if (item.Key.Equals(propertys[i].Name))
                //            {
                //                headerRow.CreateCell(cellIndex).SetCellValue(item.Value);
                //                cellIndex++;
                //                break;
                //            }
                //        }
                //    }
                //}
                #endregion
                //遍历生成excel的行集数据
                int rowIndex = headerRowNum + 1;
                if (propertyNameList == null || propertyNameList.Count == 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);
                        for (int j = 0; j < propertys.Count(); j++)
                        {
                            object obj = propertys[j].GetValue(list[i], null);
                            dataRow.CreateCell(j).SetCellValue(obj == null ? "" : obj.ToString());
                        }
                        rowIndex++;
                    }
                }
                else
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        int  cellIndex2 = 0;
                        IRow dataRow    = sheet.CreateRow(rowIndex);
                        foreach (KeyValuePair <string, string> item in propertyNameList)
                        {
                            for (int j = 0; j < propertys.Count(); j++)
                            {
                                if (item.Key.Equals(propertys[j].Name))
                                {
                                    object obj = propertys[j].GetValue(list[i], null);
                                    dataRow.CreateCell(cellIndex2).SetCellValue(obj == null ? "" : obj.ToString());
                                    cellIndex2++;
                                    break;
                                }
                            }
                        }
                        rowIndex++;
                    }
                }
                #region  面的方式可以根据传入的列的顺序导入
                //int rowIndex = 1;
                //for (int i = 0; i < list.Count; i++)
                //{
                //    IRow dataRow = sheet.CreateRow(rowIndex);
                //    int cellIndex2 = 0;
                //    for (int j = 0; j < propertys.Count(); j++)
                //    {
                //        //指定了excel表头信息
                //        if (propertyNameList.Count == 0)
                //        {
                //            object obj = propertys[j].GetValue(list[i], null);
                //            dataRow.CreateCell(j).SetCellValue(obj == null ? "" : obj.ToString());
                //        }
                //        else
                //        {
                //            foreach (KeyValuePair<string, string> item in propertyNameList)
                //            {
                //                if (item.Key.Equals(propertys[j].Name))
                //                {
                //                    object obj = propertys[j].GetValue(list[i], null);
                //                    dataRow.CreateCell(cellIndex2).SetCellValue(obj == null ? "" : obj.ToString());
                //                    cellIndex2++;
                //                    break;
                //                }
                //            }
                //        }
                //    }
                //    rowIndex++;
                //}
                #endregion

                //求合并的列数
                int rangesize = headerRow.Cells.Count;
                //合并单元格
                NPOI.SS.Util.CellRangeAddress cellRangeAddress = new NPOI.SS.Util.CellRangeAddress(0, 0, 0, rangesize - 1);
                sheet.AddMergedRegion(cellRangeAddress);
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return(ms);
            }
        }
示例#38
0
        public void DrawText(string text, IFont font, IBrush brush, CanvasPointF pointF, IDrawTextFormat format)
        {
            CheckUsability();

            _graphics.DrawString(text, (Font)font.EngineElement, (Brush)brush.EngineElement, pointF.ToGdiPointF(), (StringFormat)format?.EngineElement);
        }
示例#39
0
        public void DrawText(string text, IFont font, IBrush brush, CanvasRectangleF rectangleF)
        {
            CheckUsability();

            _graphics.DrawString(text, (Font)font.EngineElement, (Brush)brush.EngineElement, rectangleF.ToGdiRectangleF());
        }
示例#40
0
        public IDisplayCharacterRanges DisplayCharacterRanges(IFont font, IDrawTextFormat format, string text)
        {
            CheckUsability();

            return(new DisplayCharacterRanges(_graphics, (Font)font.EngineElement, (StringFormat)format.EngineElement, text));
        }
示例#41
0
        public void DrawText(string text, IFont font, IBrush brush, float x, float y, IDrawTextFormat format)
        {
            CheckUsability();

            _graphics.DrawString(text, (Font)font.EngineElement, (Brush)brush.EngineElement, x, y, (StringFormat)format?.EngineElement);
        }
示例#42
0
        public void CreateExcelFile()
        {
            //string FileName = @"d:\5.5.5.101_5555_Log_18.txt";
            string FileName = ini12.INIRead(MonkeyTestPath, "Monket Test", "Path", "") + @"\logcat.txt";

            string[]      filelist    = File.ReadAllLines(FileName, Encoding.Default);
            List <string> StringLists = new List <string>();

            for (int linenum = filelist.Length - 1; linenum >= 0; linenum--)
            {
                if (filelist[linenum].IndexOf("ANR") > -1)
                {
                    int    first = filelist[linenum].IndexOf("ANR in ") + "ANR in ".Length;
                    int    last  = filelist[linenum].LastIndexOf(" (");
                    string str2  = filelist[linenum].Substring(first, last - first);
                    StringLists.Add(str2);
                    Console.WriteLine(str2);
                }
            }

            ////建立Excel 2007檔案
            IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
            ISheet    sheet    = workbook.CreateSheet();

            //合併區
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 1, 2));
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(1, 1, 1, 2));
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(2, 2, 1, 2));
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(3, 3, 1, 2));
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(4, 4, 1, 2));
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(5, 5, 1, 2));
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(6, 6, 1, 2));
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(7, 7, 1, 2));
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(9, 9, 0, 6));   //合併Summary行
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(10, 10, 0, 5)); //合併Error List行

            //背景色(藍色)
            ICellStyle cellStyle0 = workbook.CreateCellStyle();

            cellStyle0.FillPattern         = FillPattern.SolidForeground;
            cellStyle0.FillForegroundColor = IndexedColors.PaleBlue.Index;
            cellStyle0.BorderTop           = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle0.BorderBottom        = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle0.BorderLeft          = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle0.BorderRight         = NPOI.SS.UserModel.BorderStyle.Thin;

            //背景色(綠色)
            ICellStyle cellStyle1 = workbook.CreateCellStyle();

            cellStyle1.FillPattern         = FillPattern.SolidForeground;
            cellStyle1.FillForegroundColor = IndexedColors.Lime.Index;
            cellStyle1.BorderTop           = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle1.BorderBottom        = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle1.BorderLeft          = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle1.BorderRight         = NPOI.SS.UserModel.BorderStyle.Thin;

            //背景色(粉色)
            ICellStyle cellStyle2 = workbook.CreateCellStyle();

            cellStyle2.FillPattern         = FillPattern.SolidForeground;
            cellStyle2.FillForegroundColor = IndexedColors.Tan.Index;
            cellStyle2.BorderTop           = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle2.BorderBottom        = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle2.BorderLeft          = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle2.BorderRight         = NPOI.SS.UserModel.BorderStyle.Thin;

            //背景色(灰色)
            ICellStyle cellStyle3 = workbook.CreateCellStyle();

            cellStyle3.FillPattern         = FillPattern.SolidForeground;
            cellStyle3.FillForegroundColor = IndexedColors.Grey25Percent.Index;

            //背景色(白色)
            ICellStyle cellStyle4 = workbook.CreateCellStyle();

            cellStyle4.FillPattern         = FillPattern.SolidForeground;
            cellStyle4.FillForegroundColor = IndexedColors.White.Index;

            //Summary儲存格格式
            ICellStyle summaryStyle = workbook.CreateCellStyle();
            IFont      summaryFont  = workbook.CreateFont();

            summaryFont.FontHeightInPoints = 18;
            summaryStyle.SetFont(summaryFont);
            summaryStyle.Alignment           = NPOI.SS.UserModel.HorizontalAlignment.Center;
            summaryStyle.FillPattern         = FillPattern.SolidForeground;
            summaryStyle.FillForegroundColor = IndexedColors.PaleBlue.Index;

            //A列
            sheet.CreateRow(0).CreateCell(0).SetCellValue("Project Name");
            sheet.CreateRow(1).CreateCell(0).SetCellValue("Model Name");
            sheet.CreateRow(2).CreateCell(0).SetCellValue("Start Time");
            sheet.CreateRow(3).CreateCell(0).SetCellValue("Renew Time");
            sheet.CreateRow(4).CreateCell(0).SetCellValue("SW Build Time");
            sheet.CreateRow(5).CreateCell(0).SetCellValue("Project No.");
            sheet.CreateRow(6).CreateCell(0).SetCellValue("Test Device");
            sheet.CreateRow(7).CreateCell(0).SetCellValue("Tester");
            for (int A = 0; A < 8; A++)
            {
                sheet.GetRow(A).GetCell(0).CellStyle = cellStyle0;
            }

            //E列
            sheet.GetRow(0).CreateCell(4).SetCellValue("Date");
            sheet.GetRow(1).CreateCell(4).SetCellValue("Period (H)");
            sheet.GetRow(2).CreateCell(4).SetCellValue("SW ISSUES");
            sheet.GetRow(3).CreateCell(4).SetCellValue("System Crash");
            sheet.GetRow(4).CreateCell(4).SetCellValue("Result");
            sheet.GetRow(5).CreateCell(4).SetCellValue("MTBF_SW");
            sheet.GetRow(6).CreateCell(4).SetCellValue("MTBF_Crash");
            for (int E = 0; E < 7; E++)
            {
                sheet.GetRow(E).GetCell(4).CellStyle = cellStyle0;
            }
            sheet.GetRow(4).GetCell(4).CellStyle = cellStyle4;

            //F列
            sheet.GetRow(0).CreateCell(5).SetCellValue("-----");
            sheet.GetRow(1).CreateCell(5).SetCellValue("-----");
            sheet.GetRow(2).CreateCell(5).SetCellValue("-----");
            sheet.GetRow(3).CreateCell(5).SetCellValue("-----");
            sheet.GetRow(4).CreateCell(5).SetCellValue("");
            sheet.GetRow(5).CreateCell(5).SetCellValue("-----");
            sheet.GetRow(6).CreateCell(5).SetCellValue("-----");
            for (int F = 0; F < 7; F++)
            {
                sheet.GetRow(F).GetCell(5).CellStyle = cellStyle2;
            }
            sheet.GetRow(4).GetCell(5).CellStyle = cellStyle4;

            //Summary
            sheet.CreateRow(9).CreateCell(0).SetCellValue("Summary");
            sheet.GetRow(9).GetCell(0).CellStyle = summaryStyle;

            //Error List
            sheet.CreateRow(10).CreateCell(0).SetCellValue("Error List");
            sheet.GetRow(10).GetCell(0).CellStyle = cellStyle3;

            //Total
            sheet.GetRow(10).CreateCell(6).SetCellValue("Total");
            sheet.GetRow(10).GetCell(6).CellStyle = cellStyle3;

            //搜尋相同字串並記次
            Dictionary <string, int> dict = new Dictionary <string, int>();

            foreach (string myStringList in StringLists)
            {
                if (dict.ContainsKey(myStringList))
                {
                    //如果Dictionary中存在这个关键词元素,则把这个Dictionary的key+1
                    dict[myStringList]++;
                }
                else
                {
                    //如果Dictionary中不存在这个关键词元素,则把它添加进Dictionary
                    dict.Add(myStringList, 1);
                }
            }

            int rowcnt = dict.Count;

            while (rowcnt != 0)
            {
                foreach (KeyValuePair <string, int> item in dict)
                {
                    Console.WriteLine(item.Key);
                    Console.WriteLine(item.Value);

                    sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(10 + rowcnt, 10 + rowcnt, 0, 5)); //合併Error List行
                    sheet.CreateRow(10 + rowcnt).CreateCell(0).SetCellValue(item.Key);
                    sheet.GetRow(10 + rowcnt).CreateCell(6).SetCellValue(item.Value);
                    rowcnt--;
                }
            }

            for (int c = 0; c <= 25; c++)
            {
                sheet.AutoSizeColumn(c);
            }

            FileStream file = new FileStream(ini12.INIRead(MonkeyTestPath, "Monket Test", "Path", "") + @"\MonkeyTest Report.xlsx", FileMode.Create);//產生檔案

            workbook.Write(file);
            file.Close();
        }
示例#43
0
        public MemoryStream GetMemoryStream()
        {
            MemoryStream stream = null;

            try
            {
                IWorkbook workBook = new HSSFWorkbook();

                for (int g = 0; g < _ds.Tables.Count; g++)
                {
                    DataTable dt = _ds.Tables[g];

                    ISheet sheet = workBook.CreateSheet(dt.TableName);
                    //处理表格标题
                    IRow row = sheet.CreateRow(0);
                    row.CreateCell(0).SetCellValue(dt.TableName);
                    sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Columns.Count - 1));
                    row.Height = 500;

                    ICellStyle cellStyle = workBook.CreateCellStyle();
                    IFont      font      = workBook.CreateFont();
                    font.FontName           = "微软雅黑";
                    font.FontHeightInPoints = 17;
                    cellStyle.SetFont(font);
                    cellStyle.VerticalAlignment = VerticalAlignment.Center;
                    cellStyle.Alignment         = HorizontalAlignment.Center;
                    row.Cells[0].CellStyle      = cellStyle;

                    //处理表格列头
                    row = sheet.CreateRow(1);
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
                        row.Height = 350;
                        sheet.AutoSizeColumn(i);
                    }

                    //处理数据内容
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        row        = sheet.CreateRow(2 + i);
                        row.Height = 250;
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
                            sheet.SetColumnWidth(j, 256 * 15);
                        }
                    }
                }

                stream = new MemoryStream();
                workBook.Write(stream);
                workBook.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(stream);
        }
示例#44
0
        public ActionResult ExportExcel()
        {
            string filePath = Request.MapPath("/ExcelTemplate/ZBPH.xlsx");
            //创建Excel工作薄
            XSSFWorkbook workbook = new XSSFWorkbook(filePath);
            //创建单元格样式
            ICellStyle cellStyle = workbook.CreateCellStyle();
            IFont      font      = workbook.CreateFont();

            font.FontName           = "宋体";
            font.FontHeightInPoints = 10;
            cellStyle.SetFont(font);
            //设置单元格居中显示
            cellStyle.Alignment         = HorizontalAlignment.Center;
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            //设置文本换行显示
            cellStyle.WrapText = true;
            //设置单元格边框样式
            cellStyle.BorderTop    = BorderStyle.Thin;
            cellStyle.BorderBottom = BorderStyle.Thin;
            cellStyle.BorderLeft   = BorderStyle.Thin;
            cellStyle.BorderRight  = BorderStyle.Thin;
            //创建Excel工作表
            ISheet sheet = workbook.GetSheetAt(0);
            List <TBL_JSYDBP_BCGDDJK_ZB2>    djkList      = ZB2Service.LoadEntities(t => true).OrderBy(t => t.GLID).ToList();
            List <TBL_JSYDBP_BCGDDJK_DETAIL> djkChildList = new List <TBL_JSYDBP_BCGDDJK_DETAIL>();

            foreach (var item in djkList)
            {
                var tempList = DETAILService.LoadEntities(t => t.BCGDDJKID == item.BCGDDJKID && t.OID == item.OID).ToList();
                if (tempList.Count == 0)
                {
                    djkChildList.Add(new TBL_JSYDBP_BCGDDJK_DETAIL());
                }
                else
                {
                    djkChildList.AddRange(tempList);
                }
            }
            foreach (var djk in djkList)
            {
                int count = DETAILService.LoadEntities(t => t.BCGDDJKID == djk.BCGDDJKID && t.OID == djk.OID).Count();
                count     = count == 0 ? 1 : count;
                djk.COUNT = count;
            }
            string[] pros      = { "APJSXMJZYGDDW", "YDWZ", "ZYGDDW", "ZYD", "NYD", "ZYGDMJ", "ST", "HD" };
            string[] prosChild = { "XSQ", "DKWZ", "DJTB", "DJTF", "YSMJ", "DKMJ", "QLQW", "BBH" };
            int      add       = 0;
            int      first     = 0;

            for (int i = 0; i < djkList.Count; i++)
            {
                add += (int)djkList[i].COUNT - 1;
                IRow  row   = sheet.CreateRow(i + 3 + first);
                ICell cell0 = row.CreateCell(0);
                cell0.SetCellValue(i + 1);
                CellRangeAddress regionOne = new CellRangeAddress(i + 3 + first, i + 3 + add, 0, 0);
                MergedStyle(cellStyle, sheet, regionOne);
                Type t = djkList[i].GetType();
                foreach (PropertyInfo pi in t.GetProperties())
                {
                    object value = pi.GetValue(djkList[i]);
                    string name  = pi.Name;
                    string type  = pi.PropertyType.Name;
                    for (int j = 0; j < pros.Length; j++)
                    {
                        if (name == pros[j])
                        {
                            CellRangeAddress region = new CellRangeAddress(i + 3 + first, i + 3 + add, j + 1, j + 1);
                            ICell            cell   = row.CreateCell(j + 1);
                            double           result;
                            if (value != null)
                            {
                                if ((!double.TryParse(value.ToString(), out result)) && type == "Nullable`1")
                                {
                                    cell.SetCellValue(Convert.ToDateTime(value).ToShortDateString());
                                }
                                else
                                {
                                    cell.SetCellValue(value.ToString());
                                }
                            }
                            MergedStyle(cellStyle, sheet, region);
                        }
                    }
                }
                first = add;
            }
            for (int i = 0; i < djkChildList.Count; i++)
            {
                Type t   = djkChildList[i].GetType();
                IRow row = sheet.GetRow(i + 3) == null?sheet.CreateRow(i + 3) : sheet.GetRow(i + 3);

                foreach (PropertyInfo pi in t.GetProperties())
                {
                    object value = pi.GetValue(djkChildList[i]);
                    string name  = pi.Name;
                    string type  = pi.PropertyType.Name;
                    for (int j = 0; j < prosChild.Length; j++)
                    {
                        if (name == prosChild[j])
                        {
                            ICell  cell = row.CreateCell(j + 1 + pros.Length);
                            double result;
                            if (value != null)
                            {
                                if ((!double.TryParse(value.ToString(), out result)) && type == "Nullable`1")
                                {
                                    cell.SetCellValue(Convert.ToDateTime(value).ToShortDateString());
                                }
                                else
                                {
                                    cell.SetCellValue(value.ToString());
                                }
                            }
                            cell.CellStyle = cellStyle;
                        }
                    }
                }
            }
            var ms = new NpoiMemoryStream();

            ms.AllowClose = false;
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.AllowClose = true;
            return(File(ms, "application/ vnd.ms-excel", "占补平衡项目指标使用台帐.xlsx"));
        }
示例#45
0
        public static BooleanValue <XSSFWorkbook> TwoLeveltoExcelFile(DataTable dtMain, DataTable dtSub, string mainBusiNo, string subBusiNo, bf_Query query, string joinCondition = null)
        {
            XSSFWorkbook workbook = new XSSFWorkbook();
            ISheet       sheet    = workbook.CreateSheet("Sheet1");
            IRow         head     = sheet.CreateRow(0);

            bf_Busi_Fields fieldsMain = bf_Busis.GetItem(mainBusiNo).Fields;
            bf_Busi_Fields fieldsSub  = bf_Busis.GetItem(subBusiNo).Fields;

            //新建一个字体样式对象
            IFont      font      = workbook.CreateFont();
            ICellStyle headStyle = workbook.CreateCellStyle();

            //设置字体加粗样式
            font.FontHeightInPoints = 11;
            font.FontName           = "微软雅黑";
            font.IsBold             = true;
            //使用SetFont方法将字体样式添加到单元格样式中
            headStyle.SetFont(font);

            ICellStyle  dateStyle  = workbook.CreateCellStyle();
            IDataFormat dataformat = workbook.CreateDataFormat();

            dateStyle.DataFormat = dataformat.GetFormat("yyyy-MM-dd HH:mm:ss");

            int idx       = 0;
            int colsCount = 0;

            foreach (bf_Busi_Field field in fieldsMain)
            {
                if (field.VisibleType != 1)
                {
                    continue;
                }
                ICell headCell = head.CreateCell(idx);
                headCell.SetCellValue(field.Caption);
                headCell.CellStyle = headStyle;
                idx++;
                colsCount++;
            }
            idx = 1;

            string mAlias = ((bf_Query_Item)query.Items.AsEnumerable().FirstOrDefault(s => ((bf_Query_Item)s).BusiNo == mainBusiNo)).Alias;
            string sAlias = ((bf_Query_Item)query.Items.AsEnumerable().FirstOrDefault(s => ((bf_Query_Item)s).BusiNo == subBusiNo)).Alias;

            // m.MRP_NO=s1.MRP_NO AND m.ID_NO=s1.BOM_NO
            string[] joinCd = !string.IsNullOrEmpty(joinCondition)?joinCondition.Replace(".", "_").Split(' '):
                              ((bf_Query_Item)query.Items.AsEnumerable().FirstOrDefault(s => ((bf_Query_Item)s).BusiNo == subBusiNo)).Condition.Replace(".", "_").Split(' ');
            StringBuilder sbd           = new StringBuilder();
            List <string> parrentFields = new List <string>();

            foreach (var cd in joinCd)
            {
                var items = cd.Split('=');
                if (items.Length > 1)
                {
                    var pcd = items.FirstOrDefault(f => f.ToUpper().StartsWith(mAlias.ToUpper()));
                    parrentFields.Add(pcd);
                    var ccd = items.FirstOrDefault(f => f.ToUpper().StartsWith(sAlias.ToUpper()));
                    sbd.Append(ccd);
                    sbd.Append("='{");
                    sbd.Append(parrentFields.Count() - 1);
                    sbd.Append("}'");
                }
                else
                {
                    sbd.Append(" ");
                    sbd.Append(cd);
                    sbd.Append(" ");
                }
            }

            foreach (DataRow mr in dtMain.Rows)
            {
                IRow row = sheet.CreateRow(idx);
                fillRowData(fieldsMain, mAlias, row, mr, dateStyle);
                idx++;
                head = sheet.CreateRow(idx);
                int colIdx = 1;
                foreach (bf_Busi_Field field in fieldsSub)
                {
                    if (field.VisibleType != 1)
                    {
                        continue;
                    }
                    ICell headCell = head.CreateCell(colIdx);
                    headCell.SetCellValue(field.Caption);
                    headCell.CellStyle = headStyle;
                    colIdx++;
                }
                idx++;
                DataRow[] srs = null;
                switch (parrentFields.Count)
                {
                case 1:
                    srs = dtSub.Select(string.Format(sbd.ToString(), mr[parrentFields[0]]));
                    break;

                case 2:
                    srs = dtSub.Select(string.Format(sbd.ToString(), mr[parrentFields[0]], mr[parrentFields[1]]));
                    break;

                case 3:
                    srs = dtSub.Select(string.Format(sbd.ToString(), mr[parrentFields[0]], mr[parrentFields[1]], mr[parrentFields[2]]));
                    break;

                case 4:
                    srs = dtSub.Select(string.Format(sbd.ToString(), mr[parrentFields[0]], mr[parrentFields[1]], mr[parrentFields[2]], mr[parrentFields[3]]));
                    break;
                }
                if (srs == null)
                {
                    continue;
                }

                foreach (DataRow sr in srs)
                {
                    row = sheet.CreateRow(idx);
                    fillRowData(fieldsSub, sAlias, row, sr, dateStyle, 1);
                    idx++;
                }
            }
            EXCELFileTools.SetColumnWidth(sheet, colsCount);
            return(new BooleanValue <XSSFWorkbook>(workbook));
        }
示例#46
0
        public void DrawText(string text, IFont font, IBrush brush, int x, int y)
        {
            CheckUsability();

            _graphics.DrawString(text, (Font)font.EngineElement, (Brush)brush.EngineElement, x, y);
        }
示例#47
0
        /// <summary>
        /// DataTable 导出到 Excel 的 MemoryStream
        /// </summary>
        /// <param name="workbook">源 workbook</param>
        /// <param name="dtSource">源 DataTable</param>
        /// <param name="strHeaderText">表头文本 空值未不要表头标题(多个表对应多个表头以英文逗号(,)分开,个数应与表相同)</param>
        /// <returns></returns>
        public static void ExportFromDSExcel(HSSFWorkbook workbook, DataTable dtSource, string strHeaderText)
        {
            ICellStyle  dateStyle = workbook.CreateCellStyle();
            IDataFormat format    = workbook.CreateDataFormat();

            dateStyle.DataFormat = format.GetFormat("yyyy-MM-dd HH:mm:ss");
            ISheet sheet = workbook.CreateSheet(strHeaderText);

            int[] arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
                arrColWidth[item.Ordinal] = Encoding.GetEncoding("gb2312").GetBytes(item.ColumnName.ToString()).Length;
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    int intTemp = Encoding.GetEncoding("gb2312").GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
                        arrColWidth[j] = intTemp;
                    }
                }
            }
            int rowIndex = 0;
            int intTop   = 0;

            foreach (DataRow row in dtSource.Rows)
            {
                #region 新建表、填充表头、填充列头,样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
                    if (rowIndex != 0)
                    {
                        sheet = workbook.CreateSheet();
                    }
                    intTop = 0;
                    #region 表头及样式
                    {
                        if (strHeaderText.Length > 0)
                        {
                            IRow headerRow = sheet.CreateRow(intTop);
                            intTop += 1;
                            headerRow.HeightInPoints = 25;
                            headerRow.CreateCell(0).SetCellValue(strHeaderText);
                            ICellStyle headStyle = workbook.CreateCellStyle();
                            headStyle.Alignment = HorizontalAlignment.Center;
                            IFont font = workbook.CreateFont();
                            font.FontHeightInPoints = 20;
                            font.Boldweight         = 700;
                            headStyle.SetFont(font);
                            headerRow.GetCell(0).CellStyle = headStyle;
                            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
                        }
                    }
                    #endregion
                    #region  列头及样式
                    {
                        IRow headerRow = sheet.CreateRow(intTop);
                        intTop += 1;
                        ICellStyle headStyle = workbook.CreateCellStyle();
                        headStyle.Alignment = HorizontalAlignment.Center;
                        IFont font = workbook.CreateFont();
                        font.Boldweight = 700;
                        headStyle.SetFont(font);
                        foreach (DataColumn column in dtSource.Columns)
                        {
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
                            //设置列宽
                            // sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); // 设置设置列宽 太长会报错 修改2014 年9月22日
                            int dd = (arrColWidth[column.Ordinal] + 1) * 256;

                            if (dd > 200 * 256)
                            {
                                dd = 100 * 256;
                            }


                            sheet.SetColumnWidth(column.Ordinal, dd);
                        }
                    }
                    #endregion
                    rowIndex = intTop;
                }
                #endregion
                #region 填充内容
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
                    ICell  newCell = dataRow.CreateCell(column.Ordinal);
                    string drValue = row[column].ToString();
                    switch (column.DataType.ToString())
                    {
                    case "System.String":    //字符串类型
                        newCell.SetCellValue(drValue);
                        break;

                    case "System.DateTime":    //日期类型
                        if (drValue.Length > 0)
                        {
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);
                            newCell.CellStyle = dateStyle;    //格式化显示
                        }
                        else
                        {
                            newCell.SetCellValue(drValue);
                        }
                        break;

                    case "System.Boolean":    //布尔型
                        bool boolV = false;
                        bool.TryParse(drValue, out boolV);
                        newCell.SetCellValue(boolV);
                        break;

                    case "System.Int16":
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Byte":
                        int intV = 0;
                        int.TryParse(drValue, out intV);
                        newCell.SetCellValue(intV);
                        break;

                    case "System.Decimal":
                    case "System.Double":
                        double doubV = 0;
                        double.TryParse(drValue, out doubV);
                        newCell.SetCellValue(doubV);
                        break;

                    case "System.DBNull":    //空值处理
                        newCell.SetCellValue("");
                        break;

                    default:
                        newCell.SetCellValue("");
                        break;
                    }
                }
                #endregion
                rowIndex++;
            }
        }
示例#48
0
        public void DrawText(string text, IFont font, IBrush brush, CanvasPoint point)
        {
            CheckUsability();

            _graphics.DrawString(text, (Font)font.EngineElement, (Brush)brush.EngineElement, point.ToGdiPoint());
        }
示例#49
0
        public void TestWriteSheetStyle()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
            IRow  r   = null;
            IFont fnt = wb.CreateFont();

            NPOI.SS.UserModel.ICellStyle cs  = wb.CreateCellStyle();
            NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle();

            cs.BorderBottom        = (BorderStyle.Thin);
            cs.BorderLeft          = (BorderStyle.Thin);
            cs.BorderRight         = (BorderStyle.Thin);
            cs.BorderTop           = (BorderStyle.Thin);
            cs.FillForegroundColor = ((short)0xA);
            cs.FillPattern         = FillPattern.SolidForeground;
            fnt.Color               = ((short)0xf);
            fnt.IsItalic            = (true);
            cs2.FillForegroundColor = ((short)0x0);
            cs2.FillPattern         = FillPattern.SolidForeground;
            cs2.SetFont(fnt);
            for (short rownum = (short)0; rownum < 100; rownum++)
            {
                r          = s.CreateRow(rownum);
                r.RowStyle = (cs);
                r.CreateCell(0);

                rownum++;
                if (rownum >= 100)
                {
                    break;                // I feel too lazy to Check if this isreqd :-/
                }
                r          = s.CreateRow(rownum);
                r.RowStyle = (cs2);
                r.CreateCell(0);
            }
            wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);

            SanityChecker sanityChecker = new SanityChecker();

            sanityChecker.CheckHSSFWorkbook(wb);
            Assert.AreEqual(99, s.LastRowNum, "LAST ROW == 99");
            Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW == 0");

            s = wb.GetSheetAt(0);
            Assert.IsNotNull(s, "Sheet is not null");

            for (short rownum = (short)0; rownum < 100; rownum++)
            {
                r = s.GetRow(rownum);
                Assert.IsNotNull(r, "Row is not null");

                cs = r.RowStyle;
                Assert.AreEqual(cs.BorderBottom, BorderStyle.Thin, "FillForegroundColor for row: ");
                Assert.AreEqual(cs.BorderLeft, BorderStyle.Thin, "FillPattern for row: ");
                Assert.AreEqual(cs.BorderRight, BorderStyle.Thin, "FillForegroundColor for row: ");
                Assert.AreEqual(cs.BorderTop, BorderStyle.Thin, "FillPattern for row: ");
                Assert.AreEqual(cs.FillForegroundColor, 0xA, "FillForegroundColor for row: ");
                Assert.AreEqual((short)cs.FillPattern, (short)0x1, "FillPattern for row: ");

                rownum++;
                if (rownum >= 100)
                {
                    break;                // I feel too lazy to Check if this isreqd :-/
                }
                r = s.GetRow(rownum);
                Assert.IsNotNull(r, "Row is not null");
                cs2 = r.RowStyle;
                Assert.AreEqual(cs2.FillForegroundColor, (short)0x0, "FillForegroundColor for row: ");
                Assert.AreEqual((short)cs2.FillPattern, (short)0x1, "FillPattern for row: ");
            }
        }
示例#50
0
        protected override void Process(ISheet table)
        {
            int rowNumber = 6;

            table.FindCellByMacros(titleConst).SetValue("Отчет по возможным дубликатам клиентов " + DateTime.Now.ToShortDateString());
            if (ListCheckClient == null)
            {
                table.FindCellByMacros(countConst).SetCellValue("Дубликатов нет!");
                return;
            }
            else
            {
                table.FindCellByMacros(countConst).SetCellValue(ListCheckClient.Count());
            }
            table.FindCellByMacros(countDuplicateConst).SetValue(GetNotNullString(CountDublicate.ToString()));
            table.FindCellByMacros(textCheckConst).SetValue(GetNotNullString(TextCheck));

            //создаем стиль для шапки таблицы
            ICellStyle style = table.Workbook.CreateCellStyle();

            style.BorderRight  = BorderStyle.Thin;
            style.BorderBottom = BorderStyle.Thin;
            style.BorderTop    = BorderStyle.Thin;
            style.BorderLeft   = BorderStyle.Thin;
            IFont font = table.Workbook.CreateFont();

            font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
            style.SetFont(font);

            //заполняем шапку таблицы
            IRow rowHeadTable = table.CreateRow(rowNumber - 1);
            int  colHeadTable = 0;

            if (ViewColumn.IsId)
            {
                rowHeadTable.CreateCell(colHeadTable).SetCellValue("ClientId");
                colHeadTable++;
            }
            if (ViewColumn.IsLastname)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Фамилия");
                colHeadTable++;
            }
            if (ViewColumn.IsFirstname)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Имя");
                colHeadTable++;
            }
            if (ViewColumn.IsSecondname)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Отчество");
                colHeadTable++;
            }
            if (ViewColumn.IsBirthday)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Дата рождения");
                colHeadTable++;
            }
            if (ViewColumn.IsSex)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Пол");
                colHeadTable++;
            }
            if (ViewColumn.IsPolicySeries)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Серия полиса");
                colHeadTable++;
            }
            if (ViewColumn.IsPolicyNumber)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Номер полиса");
                colHeadTable++;
            }
            if (ViewColumn.IsUnifiedPolicyNumber)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("ЕНП");
                colHeadTable++;
            }
            if (ViewColumn.IsDocumentSeries)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Серия паспорта");
                colHeadTable++;
            }
            if (ViewColumn.IsDocumentNumber)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Номер паспорта");
                colHeadTable++;
            }
            if (ViewColumn.IsLivingFullAddressString)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Адрес проживания");
                colHeadTable++;
            }
            if (ViewColumn.IsOfficialFullAddressString)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Адрес регистрации");
                colHeadTable++;
            }
            if (ViewColumn.IsTemporaryPolicyNumber)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("ВС(БСО)");
                colHeadTable++;
            }
            if (ViewColumn.IsTemporaryPolicyDate)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Дата обращения");
                colHeadTable++;
            }
            if (ViewColumn.IsSNILS)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("СНИЛС");
                colHeadTable++;
            }
            if (ViewColumn.IsPhone)
            {
                rowHeadTable.CreateCell(colHeadTable).SetValue("Телефон");
                colHeadTable++;
            }



            for (int i = 0; i < ListCheckClient.Count; i++)
            {
                int  col   = 0;
                var  check = ListCheckClient[i];
                IRow row   = table.CreateRow(rowNumber);

                if (ViewColumn.IsId)
                {
                    row.CreateCell(col).SetCellValue(check.Id);
                    col++;
                }
                if (ViewColumn.IsLastname)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.Lastname));
                    col++;
                }
                if (ViewColumn.IsFirstname)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.Firstname));
                    col++;
                }
                if (ViewColumn.IsSecondname)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.Secondname));
                    col++;
                }
                if (ViewColumn.IsBirthday)
                {
                    row.CreateCell(col).SetValue(GetDateString(check.Birthday, "dd.MM.yyyy"));
                    col++;
                }
                if (ViewColumn.IsSex)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.Sex));
                    col++;
                }
                if (ViewColumn.IsPolicySeries)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.PolicySeries));
                    col++;
                }
                if (ViewColumn.IsPolicyNumber)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.PolicyNumber));
                    col++;
                }
                if (ViewColumn.IsUnifiedPolicyNumber)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.UnifiedPolicyNumber));
                    col++;
                }
                if (ViewColumn.IsDocumentSeries)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.DocumentSeries));
                    col++;
                }
                if (ViewColumn.IsDocumentNumber)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.DocumentNumber));
                    col++;
                }
                if (ViewColumn.IsLivingFullAddressString)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.LivingFullAddressString));
                    col++;
                }
                if (ViewColumn.IsOfficialFullAddressString)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.OfficialFullAddressString));
                    col++;
                }
                if (ViewColumn.IsTemporaryPolicyNumber)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.TemporaryPolicyNumber));
                    col++;
                }
                if (ViewColumn.IsTemporaryPolicyDate)
                {
                    row.CreateCell(col).SetValue(GetDateString(check.TemporaryPolicyDate, "dd.MM.yyyy"));
                    col++;
                }
                if (ViewColumn.IsSNILS)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.SNILS));
                    col++;
                }
                if (ViewColumn.IsPhone)
                {
                    row.CreateCell(col).SetValue(GetNotNullString(check.Phone));
                    col++;
                }

                rowNumber++;
            }

            //применяем стиль для шапки таблицы
            for (int i = 0; i < colHeadTable; i++)
            {
                rowHeadTable.GetCell(i).CellStyle = style;
            }
            for (int i = 2; i < colHeadTable; i++)
            {
                table.AutoSizeColumn(i);
            }
        }
 public static void Setup()
 {
     _mBoxWindow  = IoC.Get <IWindow>();
     _font        = IoC.Get <IFont>();
     _spriteSheet = Ui.SpriteSheet;
 }
示例#52
0
 public void SetFont(IFont font)
 {
 }
示例#53
0
 /// <summary>
 /// 设置字体颜色
 /// </summary>
 /// <param name="font">字体</param>
 /// <param name="color">颜色</param>
 /// <returns></returns>
 public static IFont SetColor(this IFont font, short color)
 {
     font.Color = color;
     return(font);
 }
示例#54
0
        public static void CopyCell(HSSFCell oldCell, HSSFCell newCell, IDictionary <Int32, HSSFCellStyle> styleMap, Dictionary <short, short> paletteMap, Boolean keepFormulas)
        {
            if (styleMap != null)
            {
                if (oldCell.CellStyle != null)
                {
                    if (oldCell.Sheet.Workbook == newCell.Sheet.Workbook)
                    {
                        newCell.CellStyle = oldCell.CellStyle;
                    }
                    else
                    {
                        int styleHashCode = oldCell.CellStyle.GetHashCode();
                        if (styleMap.ContainsKey(styleHashCode))
                        {
                            newCell.CellStyle = styleMap[styleHashCode];
                        }
                        else
                        {
                            HSSFCellStyle newCellStyle = (HSSFCellStyle)newCell.Sheet.Workbook.CreateCellStyle();
                            newCellStyle.CloneStyleFrom(oldCell.CellStyle);
                            RemapCellStyle(newCellStyle, paletteMap); //Clone copies as-is, we need to remap colors manually
                            newCell.CellStyle = newCellStyle;
                            //Clone of cell style always clones the font. This makes my life easier
                            IFont theFont = newCellStyle.GetFont(newCell.Sheet.Workbook);
                            if (theFont.Color > 0 && paletteMap.ContainsKey(theFont.Color))
                            {
                                theFont.Color = paletteMap[theFont.Color]; //Remap font color
                            }
                            styleMap.Add(styleHashCode, newCellStyle);
                        }
                    }
                }
                else
                {
                    newCell.CellStyle = null;
                }
            }
            switch (oldCell.CellType)
            {
            case CellType.String:
                HSSFRichTextString rts = oldCell.RichStringCellValue as HSSFRichTextString;
                newCell.SetCellValue(rts);
                if (rts != null)
                {
                    for (int j = 0; j < rts.NumFormattingRuns; j++)
                    {
                        short fontIndex  = rts.GetFontOfFormattingRun(j);
                        int   startIndex = rts.GetIndexOfFormattingRun(j);
                        int   endIndex   = 0;
                        if (j + 1 == rts.NumFormattingRuns)
                        {
                            endIndex = rts.Length;
                        }
                        else
                        {
                            endIndex = rts.GetIndexOfFormattingRun(j + 1);
                        }
                        FontRecord fr = newCell.BoundWorkbook.CreateNewFont();
                        fr.CloneStyleFrom(oldCell.BoundWorkbook.GetFontRecordAt(fontIndex));
                        HSSFFont font = new HSSFFont((short)(newCell.BoundWorkbook.GetFontIndex(fr)), fr);
                        newCell.RichStringCellValue.ApplyFont(startIndex, endIndex, font);
                    }
                }
                break;

            case CellType.Numeric:
                newCell.SetCellValue(oldCell.NumericCellValue);
                break;

            case CellType.Blank:
                newCell.SetCellType(CellType.Blank);
                break;

            case CellType.Boolean:
                newCell.SetCellValue(oldCell.BooleanCellValue);
                break;

            case CellType.Error:
                newCell.SetCellValue(oldCell.ErrorCellValue);
                break;

            case CellType.Formula:
                if (keepFormulas)
                {
                    newCell.SetCellType(CellType.Formula);
                    newCell.CellFormula = oldCell.CellFormula;
                }
                else
                {
                    try
                    {
                        newCell.SetCellType(CellType.Numeric);
                        newCell.SetCellValue(oldCell.NumericCellValue);
                    }
                    catch (Exception)
                    {
                        newCell.SetCellType(CellType.String);
                        newCell.SetCellValue(oldCell.ToString());
                    }
                }
                break;

            default:
                break;
            }
        }
示例#55
0
        private static void MainLoop(IRenderer renderer, IFont font, IEngine sdl)
        {
            var keepRunning = true;

            while (keepRunning)
            {
                for (var evt = sdl.PollEvent(); evt != null; evt = sdl.PollEvent())
                {
                    // ReSharper disable once SwitchStatementMissingSomeCases
                    switch (evt.Type)
                    {
                    case EventType.Quit:
                        keepRunning = false;
                        break;

                    case EventType.KeyDown:
                        Console.WriteLine(evt.Key.KeySymbol.Symbol);
                        break;

                    case EventType.KeyUp:
                        Console.WriteLine("-" + evt.Key.KeySymbol.Symbol);
                        break;

                    case EventType.MouseMotion:
                        Console.WriteLine(evt.Motion.DeltaX);
                        break;

                    case EventType.MouseButtonDown:
                        Console.WriteLine(evt.Button.Button + " " + evt.Button.Clicks);
                        break;

                    case EventType.MouseWheel:
                        Console.WriteLine(evt.Wheel.Y);
                        break;
                    }
                }
                renderer.DrawColor = Color.Black;
                renderer.Clear();

                renderer.DrawColor = Color.White;
                renderer.DrawRectangle(new Rectangle {
                    X      = 10,
                    Y      = 10,
                    Width  = 10,
                    Height = 10
                });
                using (var messageSurface = font.RenderText("Hello World", Color.Red))
                    using (var messageTexture = renderer.CreateTexture(messageSurface))
                    {
                        renderer.DrawTexture(messageTexture, Point.Empty);
                    }

                using (var messageSurface = font.RenderTextWrapped("Hello World", Color.Lime, 30))
                    using (var messageTexture = renderer.CreateTexture(messageSurface))
                    {
                        renderer.DrawTexture(messageTexture, new Point(0, 50));
                    }

                using (var giraffeTextureStream = GetGiraffeStream())
                    using (var giraffeTexture = renderer.LoadTexture(giraffeTextureStream)) {
                        giraffeTexture.BlendMode = SDL_BlendMode.Alpha;
                        giraffeTexture.DrawColor = Color.FromArgb(127, 31, 31, 255);
                        renderer.DrawTexture(giraffeTexture, new Point(0, 100));
                    }

                renderer.Present();

                sdl.Delay(TimeSpan.FromSeconds(1 / 60d));
            }
        }
        public string WriteDataToSheet(string sheetName)
        {
            try
            {
                Dictionary <string, string> data = GetData();

                if (data == null || data?.Count == 0)
                {
                    System.Windows.MessageBox.Show("未发现有效数据", "Error");
                    OnReportPercentage(new ReportPercentageEventArgs {
                        Phase = "进度", Percentage = 0
                    });
                    return("");
                }
                ISheet sheet = _workbook.CreateSheet(string.IsNullOrWhiteSpace(sheetName) ? "NewSheet" : sheetName);

                ICellStyle headerStyle = _workbook.CreateCellStyle();
                headerStyle.Alignment         = HorizontalAlignment.Center;
                headerStyle.VerticalAlignment = VerticalAlignment.Center;
                //headerStyle.BorderTop = BorderStyle.Thin;
                //headerStyle.BorderBottom = BorderStyle.Thin;
                //headerStyle.BorderLeft = BorderStyle.Thin;
                //headerStyle.BorderRight = BorderStyle.Thin;
                IFont headerFont = _workbook.CreateFont();
                headerFont.IsBold             = true;
                headerFont.FontHeightInPoints = 12;
                headerFont.FontName           = "微软雅黑";
                headerStyle.SetFont(headerFont);

                ICellStyle contentStyle = _workbook.CreateCellStyle();
                contentStyle.Alignment         = HorizontalAlignment.Center;
                contentStyle.VerticalAlignment = VerticalAlignment.Center;
                contentStyle.BorderTop         = BorderStyle.Thin;
                contentStyle.BorderBottom      = BorderStyle.Thin;
                contentStyle.BorderLeft        = BorderStyle.Thin;
                contentStyle.BorderRight       = BorderStyle.Thin;
                IFont contentFont = _workbook.CreateFont();
                contentFont.FontHeightInPoints = 11;
                contentFont.FontName           = "微软雅黑";
                contentStyle.SetFont(contentFont);

                int cur_row = 0;
                foreach (var item in data)
                {
                    //写首行数据,编码和名称
                    IRow  row       = sheet.CreateRow(cur_row);
                    ICell cell_code = row.CreateCell(0, CellType.String);
                    cell_code.CellStyle = headerStyle;
                    cell_code.SetCellValue(item.Key);
                    ICell cell_name = row.CreateCell(1, CellType.String);
                    cell_name.CellStyle = headerStyle;
                    cell_name.SetCellValue(item.Value);
                    CellRangeAddress cellRangeAddress = new CellRangeAddress(cur_row, cur_row, 1, 5);
                    sheet.AddMergedRegion(cellRangeAddress);

                    //写固定数据,每个首行后面4行都一样
                    for (int i = 1; i <= 4; ++i)
                    {
                        IRow  fixed_row   = sheet.CreateRow(cur_row + i);
                        ICell fixed_cell0 = fixed_row.CreateCell(0, CellType.String);
                        fixed_cell0.CellStyle = contentStyle;
                        fixed_cell0.SetCellValue("几何信息深度");

                        ICell fixed_cell1 = fixed_row.CreateCell(1, CellType.String);
                        fixed_cell1.CellStyle = contentStyle;
                        fixed_cell1.SetCellValue($"G{i}");

                        ICell fixed_cell2 = fixed_row.CreateCell(2, CellType.String);
                        fixed_cell2.CellStyle = contentStyle;

                        ICell fixed_cell3 = fixed_row.CreateCell(3, CellType.String);
                        fixed_cell3.CellStyle = contentStyle;
                        fixed_cell3.SetCellValue("非几何信息深度");

                        ICell fixed_cell4 = fixed_row.CreateCell(4, CellType.String);
                        fixed_cell4.CellStyle = contentStyle;
                        fixed_cell4.SetCellValue($"N{i}");

                        ICell fixed_cell5 = fixed_row.CreateCell(5, CellType.String);
                        fixed_cell5.CellStyle = contentStyle;
                    }
                    CellRangeAddress cellRangeAddress_geo = new CellRangeAddress(cur_row + 1, cur_row + 4, 0, 0);
                    sheet.AddMergedRegion(cellRangeAddress_geo);
                    CellRangeAddress cellRangeAddress_non_geo = new CellRangeAddress(cur_row + 1, cur_row + 4, 3, 3);
                    sheet.AddMergedRegion(cellRangeAddress_non_geo);

                    OnReportPercentage(new ReportPercentageEventArgs {
                        Phase = "写入数据", Percentage = (int)Math.Ceiling((float)cur_row / 5 / data.Count * 100)
                    });
                    System.Diagnostics.Debug.WriteLine((int)Math.Ceiling((float)cur_row / 5 / data.Count * 100));
                    cur_row += 5;
                }

                //int last = sheet.GetRow(1).LastCellNum;
                //for (int i = 0; i < last; ++i)
                //{
                //    OnReportPercentage(new ReportPercentageEventArgs { Phase = "格式化数据", Percentage = (int)Math.Ceiling((float)i / last * 100) });
                //    sheet.AutoSizeColumn(i, true);
                //}
                sheet.SetColumnWidth(0, 26 * 256);
                sheet.SetColumnWidth(1, 7 * 256);
                sheet.SetColumnWidth(2, 7 * 256);
                sheet.SetColumnWidth(3, 20 * 256);
                sheet.SetColumnWidth(4, 7 * 256);
                sheet.SetColumnWidth(5, 7 * 256);

                string savePath = "";
                string rgb      = $"R{_rgb[0].ToString()}G{_rgb[1].ToString()}B{_rgb[2].ToString()}";
                if (_filePath.EndsWith(".xls"))
                {
                    savePath = _filePath.Replace(".xls", $"_new_{rgb}.xls");
                }
                else if (_filePath.EndsWith(".xlsx"))
                {
                    savePath = _filePath.Replace(".xlsx", $"_new_{rgb}.xlsx");
                }
                OnReportPercentage(new ReportPercentageEventArgs {
                    Phase = "正在写入文件", Percentage = 0
                });
                WriteToFile(savePath);
                OnReportPercentage(new ReportPercentageEventArgs {
                    Phase = "完成", Percentage = 100
                });
                return(savePath);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message + "\n------\nTargetSite:\n" + ex.TargetSite.ToString() + "\n------\nStackTrace:\n" + ex.StackTrace, "Error");
                return("");
            }
        }
示例#57
0
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="savepath">导出文件完整路径(包括文件名)</param>
        /// <param name="dt">数据源</param>
        /// <param name="widths">列宽集合</param>
        public static void ExportExcel(string savePath, DataTable dt, string title, List <int> widths = null)
        {
            IWorkbook book = null;

            book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            ISheet sheet = book.CreateSheet("数据清单");

            var headerIndex = 0;

            if (title.Length > 0)
            {
                //第1行添加标题
                sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Rows[0].ItemArray.Length - 1));
                headerIndex = 1;
            }
            //设置行高   Height的单位是1/20个点。例:设置高度为30个点
            IRow row = sheet.CreateRow(0);

            row.Height = 30 * 20;


            ICell titleCell = row.CreateCell(0);

            titleCell.SetCellValue(title);
            titleCell.CellStyle.Alignment         = HorizontalAlignment.Left;
            titleCell.CellStyle.VerticalAlignment = VerticalAlignment.Center;
            IFont titleFont = book.CreateFont();

            titleFont.FontHeightInPoints = 11;
            titleCell.CellStyle.SetFont(titleFont);

            if (widths != null)
            {
                //设置列宽
                for (int i = 0; i < widths.Count; i++)
                {
                    sheet.SetColumnWidth(i, widths[i] * 256); //列宽单位为 1/256个字符
                }
            }

            int index = 0;

            // 添加表头
            row = sheet.CreateRow(headerIndex);
            foreach (DataColumn item in dt.Columns)
            {
                ICell cell = row.CreateCell(index);
                cell.SetCellType(CellType.String);
                cell.SetCellValue(item.Caption);
                index++;
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                index = 0;
                row   = sheet.CreateRow(i + headerIndex + 1); // 添加数据  从第3行开始
                foreach (DataColumn item in dt.Columns)
                {
                    ICell cell = row.CreateCell(index);
                    cell.SetCellType(CellType.String);
                    cell.SetCellValue(dt.Rows[i][item.ColumnName].ToString());
                    index++;
                }
            }

            // 写入
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            book = null;

            using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write))
            {
                byte[] data = ms.ToArray();
                fs.Write(data, 0, data.Length);
                fs.Flush();
            }
            ms.Close();
            ms.Dispose();
        }
示例#58
0
文件: SheetUtil.cs 项目: twxstar/npoi
        /**
         * Compute width of a single cell
         *
         * @param cell the cell whose width is to be calculated
         * @param defaultCharWidth the width of a single character
         * @param formatter formatter used to prepare the text to be measured
         * @param useMergedCells    whether to use merged cells
         * @return  the width in pixels
         */
        public static double GetCellWidth(ICell cell, int defaultCharWidth, DataFormatter formatter, bool useMergedCells)
        {
            ISheet    sheet  = cell.Sheet;
            IWorkbook wb     = sheet.Workbook;
            IRow      row    = cell.Row;
            int       column = cell.ColumnIndex;

            int colspan = 1;

            for (int i = 0; i < sheet.NumMergedRegions; i++)
            {
                CellRangeAddress region = sheet.GetMergedRegion(i);
                if (ContainsCell(region, row.RowNum, column))
                {
                    if (!useMergedCells)
                    {
                        // If we're not using merged cells, skip this one and move on to the next.
                        return(-1);
                    }
                    cell    = row.GetCell(region.FirstColumn);
                    colspan = 1 + region.LastColumn - region.FirstColumn;
                }
            }

            ICellStyle style       = cell.CellStyle;
            CellType   cellType    = cell.CellType;
            IFont      defaultFont = wb.GetFontAt((short)0);
            Font       windowsFont = IFont2Font(defaultFont);

            // for formula cells we compute the cell width for the cached formula result
            if (cellType == CellType.Formula)
            {
                cellType = cell.CachedFormulaResultType;
            }

            IFont font = wb.GetFontAt(style.FontIndex);

            //AttributedString str;
            //TextLayout layout;

            double width = -1;

            using (Bitmap bmp = new Bitmap(2048, 100))
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    if (cellType == CellType.String)
                    {
                        IRichTextString rt    = cell.RichStringCellValue;
                        String[]        lines = rt.String.Split("\n".ToCharArray());
                        for (int i = 0; i < lines.Length; i++)
                        {
                            String txt = lines[i] + defaultChar;

                            //str = new AttributedString(txt);
                            //copyAttributes(font, str, 0, txt.length());
                            windowsFont = IFont2Font(font);
                            if (rt.NumFormattingRuns > 0)
                            {
                                // TODO: support rich text fragments
                            }

                            //layout = new TextLayout(str.getIterator(), fontRenderContext);
                            if (style.Rotation != 0)
                            {
                                /*
                                 * Transform the text using a scale so that it's height is increased by a multiple of the leading,
                                 * and then rotate the text before computing the bounds. The scale results in some whitespace around
                                 * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
                                 * is added by the standard Excel autosize.
                                 */
                                //AffineTransform trans = new AffineTransform();
                                //trans.concatenate(AffineTransform.getRotateInstance(style.Rotation*2.0*Math.PI/360.0));
                                //trans.concatenate(
                                //    AffineTransform.getScaleInstance(1, fontHeightMultiple)
                                //    );
                                double angle = style.Rotation * 2.0 * Math.PI / 360.0;
                                SizeF  sf    = g.MeasureString(txt, windowsFont);
                                double x1    = Math.Abs(sf.Height * Math.Sin(angle));
                                double x2    = Math.Abs(sf.Width * Math.Cos(angle));
                                double w     = Math.Round(x1 + x2, 0, MidpointRounding.ToEven);
                                width = Math.Max(width, (w / colspan / defaultCharWidth) * 2 + cell.CellStyle.Indention);
                                //width = Math.Max(width,
                                //                 ((layout.getOutline(trans).getBounds().getWidth()/colspan)/defaultCharWidth) +
                                //                 cell.getCellStyle().getIndention());
                            }
                            else
                            {
                                //width = Math.Max(width,
                                //                 ((layout.getBounds().getWidth()/colspan)/defaultCharWidth) +
                                //                 cell.getCellStyle().getIndention());
                                double w = Math.Round(g.MeasureString(txt, windowsFont).Width, 0, MidpointRounding.ToEven);
                                width = Math.Max(width, (w / colspan / defaultCharWidth) * 2 + cell.CellStyle.Indention);
                            }
                        }
                    }
                    else
                    {
                        String sval = null;
                        if (cellType == CellType.Numeric)
                        {
                            // Try to get it formatted to look the same as excel
                            try
                            {
                                sval = formatter.FormatCellValue(cell, dummyEvaluator);
                            }
                            catch (Exception)
                            {
                                sval = cell.NumericCellValue.ToString();
                            }
                        }
                        else if (cellType == CellType.Boolean)
                        {
                            sval = cell.BooleanCellValue.ToString().ToUpper();
                        }
                        if (sval != null)
                        {
                            String txt = sval + defaultChar;
                            //str = new AttributedString(txt);
                            //copyAttributes(font, str, 0, txt.length());
                            windowsFont = IFont2Font(font);
                            //layout = new TextLayout(str.getIterator(), fontRenderContext);
                            if (style.Rotation != 0)
                            {
                                /*
                                 * Transform the text using a scale so that it's height is increased by a multiple of the leading,
                                 * and then rotate the text before computing the bounds. The scale results in some whitespace around
                                 * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
                                 * is added by the standard Excel autosize.
                                 */
                                //AffineTransform trans = new AffineTransform();
                                //trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
                                //trans.concatenate(
                                //    AffineTransform.getScaleInstance(1, fontHeightMultiple)
                                //    );
                                //width = Math.max(width,
                                //                 ((layout.getOutline(trans).getBounds().getWidth()/colspan)/defaultCharWidth) +
                                //                 cell.getCellStyle().getIndention());
                                double angle = style.Rotation * 2.0 * Math.PI / 360.0;
                                SizeF  sf    = g.MeasureString(txt, windowsFont);
                                double x1    = sf.Height * Math.Sin(angle);
                                double x2    = sf.Width * Math.Cos(angle);
                                double w     = Math.Round(x1 + x2, 0, MidpointRounding.ToEven);
                                width = Math.Max(width, (w / colspan / defaultCharWidth) * 2 + cell.CellStyle.Indention);
                            }
                            else
                            {
                                //width = Math.max(width,
                                //                 ((layout.getBounds().getWidth()/colspan)/defaultCharWidth) +
                                //                 cell.getCellStyle().getIndention());
                                double w = Math.Round(g.MeasureString(txt, windowsFont).Width, 0, MidpointRounding.ToEven);
                                width = Math.Max(width, (w * 1.0 / colspan / defaultCharWidth) * 2 + cell.CellStyle.Indention);
                            }
                        }
                    }
                }
            return(width);
        }
示例#59
0
        public Stream ToExcel()
        {
            int rowIndex = 0;
            //创建workbook
            HSSFWorkbook workbook = new HSSFWorkbook();
            MemoryStream ms       = new MemoryStream();
            ISheet       sheet    = workbook.CreateSheet("sheet1");
            IRow         row      = sheet.CreateRow(rowIndex);

            row.Height = 200 * 3;

            //表头样式
            ICellStyle style = workbook.CreateCellStyle();

            style.Alignment = HorizontalAlignment.LEFT;//居中对齐
            //表头单元格背景色
            style.FillForegroundColor = HSSFColor.LIGHT_GREEN.index;
            style.FillPattern         = FillPatternType.SOLID_FOREGROUND;
            //表头单元格边框
            style.BorderTop         = CellBorderType.THIN;
            style.TopBorderColor    = HSSFColor.BLACK.index;
            style.BorderRight       = CellBorderType.THIN;
            style.RightBorderColor  = HSSFColor.BLACK.index;
            style.BorderBottom      = CellBorderType.THIN;
            style.BottomBorderColor = HSSFColor.BLACK.index;
            style.BorderLeft        = CellBorderType.THIN;
            style.LeftBorderColor   = HSSFColor.BLACK.index;
            style.VerticalAlignment = VerticalAlignment.CENTER;
            //表头字体设置
            IFont font = workbook.CreateFont();

            font.FontHeightInPoints = 12;  //字号
            font.Boldweight         = 600; //加粗
            //font.Color = HSSFColor.WHITE.index;//颜色
            style.SetFont(font);

            //数据样式
            ICellStyle datastyle = workbook.CreateCellStyle();

            datastyle.Alignment = HorizontalAlignment.LEFT;//左对齐
            //数据单元格的边框
            datastyle.BorderTop         = CellBorderType.THIN;
            datastyle.TopBorderColor    = HSSFColor.BLACK.index;
            datastyle.BorderRight       = CellBorderType.THIN;
            datastyle.RightBorderColor  = HSSFColor.BLACK.index;
            datastyle.BorderBottom      = CellBorderType.THIN;
            datastyle.BottomBorderColor = HSSFColor.BLACK.index;
            datastyle.BorderLeft        = CellBorderType.THIN;
            datastyle.LeftBorderColor   = HSSFColor.BLACK.index;
            //数据的字体
            IFont datafont = workbook.CreateFont();

            datafont.FontHeightInPoints = 11;//字号
            datastyle.SetFont(datafont);
            //设置列宽
            sheet.SetColumnWidth(0, 20 * 256);

            sheet.DisplayGridlines = false;

            try
            {
                //表头数据
                for (int i = 0; i < titles.Length; i++)
                {
                    ICell cell = row.CreateCell(i);
                    cell.SetCellValue(titles[i]);
                    cell.CellStyle = style;
                }
                for (int k = 0; k < data.Rows.Count; k++)
                {
                    row        = sheet.CreateRow(k + 1);
                    row.Height = 200 * 2;
                    for (int j = 0; j < data.Columns.Count; j++)
                    {
                        ICell cell = row.CreateCell(j);
                        cell.SetCellValue(data.Rows[k][j].ToString());
                        cell.CellStyle = datastyle;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                workbook    = null;
                sheet       = null;
                row         = null;
            }
            return(ms);
        }
        private void exportarDataExecl(eInterfaceContableVC e)
        {
            bInterfaceContableVC bc     = new bInterfaceContableVC();
            DataTable            dtlist = bc.GetSelectContableExport(e);

            String filename = "Registro Contable " + ddl_contrato_i.SelectedItem.Text + "-" + ddl_tip_operacion_i.SelectedItem.Text + System.DateTime.Today.ToShortDateString() + ".xls";

            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            Response.Clear();

            var output = new MemoryStream();
            var writer = new StreamWriter(output);

            HSSFWorkbook xssfworkbook = new HSSFWorkbook();
            ISheet       sheet        = xssfworkbook.CreateSheet("INTERFACE " + ddl_tip_operacion_i.SelectedItem.Text.ToUpper());

            IFont titleFont = xssfworkbook.CreateFont();

            titleFont.FontName           = "Calibri";
            titleFont.Boldweight         = (short)FontBoldWeight.Bold;
            titleFont.Color              = (IndexedColors.Black.Index);
            titleFont.FontHeightInPoints = 11;

            ICellStyle styleCabecera = xssfworkbook.CreateCellStyle();

            styleCabecera.Alignment         = HorizontalAlignment.Center;
            styleCabecera.VerticalAlignment = VerticalAlignment.Center;
            styleCabecera.SetFont(titleFont);
            styleCabecera.BorderTop    = NPOI.SS.UserModel.BorderStyle.Thin;
            styleCabecera.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            styleCabecera.BorderLeft   = NPOI.SS.UserModel.BorderStyle.Thin;
            styleCabecera.BorderRight  = NPOI.SS.UserModel.BorderStyle.Thin;
            for (int cl1 = 0; cl1 < 11; cl1++)
            {
                sheet.SetColumnWidth(cl1, 150 * 25);
            }
            for (int cl = 11; cl <= 21; cl++)
            {
                sheet.SetColumnWidth(cl, 300 * 25);
            }

            IRow  dataHeader = sheet.CreateRow(0);
            ICell dataCellH;

            for (int h = 0; h < dtlist.Columns.Count; h++)
            {
                dataCellH = dataHeader.CreateCell(h);
                dataCellH.SetCellValue(dtlist.Columns[h].ToString());
                dataCellH.CellStyle          = styleCabecera;
                dataCellH.CellStyle.WrapText = true;
            }
            for (int r = 0; r < dtlist.Rows.Count; r++)
            {
                IRow dataBody = sheet.CreateRow(1 + r);
                for (int c = 0; c < dtlist.Columns.Count; c++)
                {
                    dataBody.CreateCell(c, CellType.String).SetCellValue(dtlist.Rows[r][c].ToString());
                }
            }
            xssfworkbook.Write(output);
            writer.Flush();

            dtlist.Rows.Clear();
            dtlist.Columns.Clear();
            dtlist.Clear();

            Response.BinaryWrite(output.GetBuffer());
            Response.End();
        }