Пример #1
0
            /// <summary>
            /// 设置单元格值,支持合并单元格
            /// </summary>
            /// <param name="firstRow"></param>
            /// <param name="lastRow"></param>
            /// <param name="firstCol"></param>
            /// <param name="lastCol"></param>
            /// <param name="value"></param>
            /// <param name="sheet"></param>
            public void SetCellValue(int firstRow, int lastRow, int firstCol, int lastCol, object value, NPOI.SS.UserModel.ISheet sheet)
            {
                NPOI.SS.UserModel.IRow  row  = null;
                NPOI.SS.UserModel.ICell cell = null;

                for (int r = firstRow; r <= lastRow; r++)
                {
                    row = sheet.GetRow(r);
                    if (row == null)
                    {
                        row = sheet.CreateRow(r);
                    }
                    for (int c = firstCol; c <= lastCol; c++)
                    {
                        cell = row.GetCell(c);
                        if (cell == null)
                        {
                            cell = row.CreateCell(c);
                        }
                    }
                }
                sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(firstRow, lastRow, firstCol, lastCol));

                row  = sheet.GetRow(firstRow);
                cell = row.GetCell(firstCol);
                if (value is bool)
                {
                    cell.SetCellValue((bool)value);
                }
                if (value is string)
                {
                    string svalue = (string)value;
                    if (svalue != null && svalue != "" && svalue.Substring(0, 1) == "=")
                    {
                        cell.SetCellFormula(svalue.Substring(1));
                    }
                    else
                    {
                        cell.SetCellValue((string)svalue);
                    }
                }
                if (value is NPOI.SS.UserModel.IRichTextString)
                {
                    cell.SetCellValue((NPOI.SS.UserModel.IRichTextString)value);
                }
                if (value is DateTime)
                {
                    if (this.DateTimeCellStyle != null)
                    {
                        cell.CellStyle = this.DateTimeCellStyle;
                    }
                    cell.SetCellValue((DateTime)value);
                }
                if (value is double)
                {
                    cell.SetCellValue((double)value);
                }
                if (value is int)
                {
                    cell.SetCellValue((int)value);
                }
            }