C# NPOI 将单元格样式设置为文本/字符串 1-19 被格式化为日期/禁用任何格式

C# NPOI set cell style to Text / string 1-19 is formatted as a date / disable any formating

我正在创建一个 excel,当我写一些值示例 1-19 时,当我打开 excel 文档时,我看到 1-19,但是如果我点击它然后 excel 尝试将其格式化为日期

有没有办法强制 sheet 不使用任何公式或格式? 我检查过,数据格式是字符串。

 private void Test1(ref ISheet worksheet, string[] array, IWorkbook workbook, int iRow, XSSFFont font2)
        {
            var format = HSSFDataFormat.GetBuiltinFormats();

            ICellStyle _TextCellStyle = workbook.CreateCellStyle();
            _TextCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("@");
            IRow file = worksheet.CreateRow(iRow);
            int iCol = 0;
            for (int y = 0; y < array.Length; y++)
            {
                ICellStyle style = workbook.CreateCellStyle();

                style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
                //style.DataFormat = HSSFDataFormat.
                ICell cell = file.CreateCell(iCol, CellType.String);
                cell.SetCellValue(array[y]);
                style.SetFont(font2);
               // cell.CellStyle = style;
                var getst = cell.CellType;
                cell.CellStyle = _TextCellStyle;
                iCol++;
                getst = cell.CellType;

            }

        }

即使您按照文档使用了正确的格式字符串“@”,您的数据仍保持 "General" 格式。有时库方法在 NPOI 中不起作用,因此您必须尝试不同的方法。

您可以尝试其中之一

 _TextCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("text"); //Instead of "@"

或者在为 excel 文件写入数据时为数据添加前缀单引号,例如 '1-19