Reputation: 203
I have one requirement that 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;
Upvotes: 2
Views: 1710
Reputation: 1
Please check the data type of cell.SetCellValue
.
cell.SetCellValue(double)
.cell.SetCellValue(String)
might cause your issue.
Upvotes: 0
Reputation: 5822
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);
}
Upvotes: 1
Reputation: 117
Ok so from what I understand you need, this should do the trick:
Lets say you want to add the date and time to cell A1, here is how i went about it and it worked:
xl.range cellA1 = yourWorksheet.Cells[1,1];
cellA1.Formula = "=NOW()";
CellA1.Value = CellA1.Value;
CellA1.NumberFormat = "m/d/yyyy";
After this you should be left with your cell showing only the date, and inside the cell you should have the time aswell. Hope this helps.
Upvotes: 0