Esempio n. 1
0
        /// <summary>
        /// 创建单元格样式。
        /// </summary>
        /// <param name="workbook">工作表对象</param>
        /// <param name="styleCallback">单元格样式设置回调</param>
        /// <param name="fontCallback">字体设置回调</param>
        /// <param name="borderStyle">边框样式</param>
        /// <returns>单元格样式对象</returns>
        public static ICellStyle NewCellStyle(this IWorkbook workbook,
            Action<ICellStyle> styleCallback = null, Action<IFont> fontCallback = null, BorderStyle borderStyle = BorderStyle.Thin)
        {
            var font = workbook.CreateFont();
            var style = workbook.CreateCellStyle();

            font.FontName = "Courier New";
            font.FontHeightInPoints = 12;

            style.WrapText = false;
            style.Alignment = HorizontalAlignment.Center;
            style.VerticalAlignment = VerticalAlignment.Center;

            style.BorderLeft = borderStyle;
            style.BorderTop = borderStyle;
            style.BorderRight = borderStyle;
            style.BorderBottom = borderStyle;

            fontCallback?.Invoke(font);
            styleCallback?.Invoke(style);

            style.SetFont(font);

            return style;
        }
Esempio n. 2
0
        public static void SetCellValue(this IWorkbook workbook, ICell cell, object cellValue)
        {
            var colType = cellValue != null ? cellValue.GetType() : null;

            if (colType == null || cellValue is DBNull) return;

            if (_numericTypes.Contains(colType))
            {
                cell.SetCellType(CellType.NUMERIC);
                cell.SetCellValue(Convert.ToDouble(cellValue));
            }
            else if (_stringConvertableTypes.Contains(colType))
            {
                cell.SetCellValue(cellValue.ToString());
            }
            else if (colType == typeof(DateTime))
            {
                var style = workbook.CreateCellStyle();
                var format = workbook.CreateDataFormat();
                const string dateFormat = "dd MMM yyyy hh:mm:ss";

                cell.SetCellValue(((DateTime)cellValue).ToString(dateFormat));
                style.DataFormat = format.GetFormat(dateFormat);
                cell.SetCellType(CellType.STRING);
                cell.CellStyle = style;
            }
            else
            {
                var toStringMethod = colType.GetMethod("ToString", BindingFlags.Public);

                if (toStringMethod != null && toStringMethod.DeclaringType != typeof(object))
                {
                    // Has custom ToString method
                    cell.SetCellValue(cellValue.ToString());
                }
            }
        }