Search code examples
excelc#-4.0npoi

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


I am creating an excel, when i write some values example 1-19, when I open the excel doc, i see 1-19, but if i click on it then excel tries to format it as a date

IS THERE A WAY to force the sheet to not use any formulas or formatting? I have checked and the dataformat is string.

 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;

            }

        }

Solution

  • Your data remains in "General" format even after you are using correct format string "@" as per documentation. Some time library methods don't work in NPOI so you'll have to try different approach.

    You can try one of these

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

    Or prefix single quote for data when writing it for excel file like '1-19