Search code examples
c#exceldatedatetimenpoi

After double click over excel only format is getting applied over excel in npoi in C#


I have one requirement that requirement where NPOI cell value is in format of "MM/dd/yy" and when user click on that specific cell, it should show complete value as shown into image.

When i try to do manually, it works absolutely fine but when i apply through code. It does not work.

I am attaching sample code below for reference purpose. So you can guide me for possible solution. I will really appreciate your help and support. Thanks in advance.

string value = "02/17/2017 10:10:10";
 DateTime datetime;
 SimpleDateFormat dateFormat = new SimpleDateFormat ("MM/dd/yy");
 DateTime dt = Convert.ToDateTime(value);
 var dateString = dateFormat.Format(dt, CultureInfo.InvariantCulture);
 if (DateTime.TryParseExact(dateString.ToString(), "MM/dd/yy",      CultureInfo.InvariantCulture, DateTimeStyles.None, out datetime))
 {
       cell.SetCellValue(datetime.Date);
 }
 else
 {
         cell.SetCellValue(value);
 }

//For styling
var dateTypecontentStyle = workbook.CreateCellStyle();
 dateTypecontentStyle.DataFormat = dataFormatCustom.GetFormat("MM/dd/yy");
 cell.CellStyle = dateTypecontentStyle;

Solution

  • Set the date format of the cell as MM/dd/yy, then set the full date in the cell. The cell should display the date as MM/dd/yy but display the full date when the cell is selected.

    Try this code:

    DateTime dateTest = DateTime.ParseExact("02/17/2017 10:10:10", "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
    
    using (FileStream fs = new FileStream(@"C:\temp\test.xlsx", FileMode.Create, FileAccess.Write))
    {
        IWorkbook workbook = new XSSFWorkbook();
        ISheet sheet = workbook.CreateSheet("sheet");
    
        IRow row = sheet.CreateRow(0);
    
        ICell cell = row.CreateCell(0);
        ICellStyle cellStyle = workbook.CreateCellStyle();
        cellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("MM/dd/yy"); 
        cell.CellStyle = cellStyle;
        cell.SetCellValue(dateTest);
    
        workbook.Write(fs);
    }