예제 #1
0
        /// <summary>
        /// 自动设置列宽
        /// </summary>
        /// <param name="sheet"></param>
        private void AutoSizeColumns(XLSheet sheet)
        {
            using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
            {
                for (int c = 0; c < sheet.Columns.Count; c++)
                {
                    int colWidth = -1;
                    for (int r = 0; r < sheet.Rows.Count; r++)
                    {
                        object value = sheet[r, c].Value;
                        if (value != null)
                        {
                            // get value (unformatted at this point)
                            string text = value.ToString();

                            // format value if cell has a style with format set
                            C1.C1Excel.XLStyle s = sheet[r, c].Style;
                            if (s != null && s.Format.Length > 0 && value is IFormattable)
                            {
                                string fmt = XLStyle.FormatXLToDotNet(s.Format);
                                text = ((IFormattable)value).ToString(fmt, CultureInfo.CurrentCulture);
                            }

                            // get font (default or style)
                            Font font = this.c1XLBook1.DefaultFont;
                            if (s != null && s.Font != null)
                            {
                                font = s.Font;
                            }

                            // measure string (add a little tolerance)
                            Size sz = Size.Ceiling(g.MeasureString(text + "XX", font));

                            // keep widest so far
                            if (sz.Width > colWidth)
                            {
                                colWidth = sz.Width;
                            }
                        }
                    }

                    // done measuring, set column width
                    if (colWidth > -1)
                    {
                        sheet.Columns[c].Width = C1XLBook.PixelsToTwips(colWidth);
                    }
                }
            }
        }
        public static void MergeCells(ref C1.C1Excel.XLSheet sheet, C1.C1Excel.XLStyle style, int rowFrom, int rowTo, int colForm, int colTo, object value)
        {
            if (style == null)
            {
                throw new ArgumentNullException("style", "style is null.");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value", "value is null.");
            }

            for (int x = rowFrom; x <= rowTo; x++)
            {
                for (int y = colForm; y <= colTo; y++)
                {
                    sheet[x, y].Style = style;
                }
            }

            sheet.MergedCells.Add(new C1.C1Excel.XLCellRange(rowFrom, rowTo, colForm, colTo));
            sheet[rowFrom, colForm].Value = value;
        }