代码之家  ›  专栏  ›  技术社区  ›  jstuardo

AutoSizeColumn适用于除包含日期时间值的列以外的所有列

  •  0
  • jstuardo  · 技术社区  · 5 年前

    我正在使用NPOI创建一个Excel文件。

            var workbook = new XSSFWorkbook();
            var sheet = workbook.CreateSheet(title);
    

    Excel中填充了数据。相关部分是在设置日期和时间值时:

                            if (data is DateTime)
                            {
                                cell.CellStyle = GetDateTimeStyle(workbook, true, GetCustomFormatForColumn(column));
                                cell.SetCellValue(Convert.ToDateTime(data));
                            }
    

    ICell cell = row.CreateCell(column); GetDateTimeStyle 方法是:

        private ICellStyle GetDateTimeStyle(XSSFWorkbook wb, bool useBorder, string customFormat)
        {
            if (!_styles.TryGetValue("DATETIME", out ICellStyle style))
            {
                style = wb.CreateCellStyle();
                style.SetFont(GetItemFont(wb));
    
                style.Alignment = HorizontalAlignment.Center;
    
                if (useBorder)
                    SetBorder(style);
    
                if (!String.IsNullOrEmpty(customFormat))
                    style.DataFormat = wb.CreateDataFormat().GetFormat(customFormat);
                else
                    style.DataFormat = wb.CreateDataFormat().GetFormat("dd/MM/yyyy HH:mm:ss");
    
                _styles.Add("DATETIME", style);
            }
    
            return style;
        }
    

    在所有单元格填充完毕后,我运行这个 for

            column = 0;
            foreach (string header in columnNames)
                sheet.AutoSizeColumn(column++);
    

    之后,生成的Excel会自动调整所有列的大小,但包含日期和时间值的列除外。

    包含日期和时间值的单元格在宽度上展开,但仍有一些像素需要展开,以便显示整个日期和时间,而不是仅仅显示 ######### .

    当做

    0 回复  |  直到 5 年前