Quantcast
Channel: NPOI
Viewing all articles
Browse latest Browse all 1621

New Post: How can I change the long date format to short date format?

$
0
0
This is working well for me, using your code I added date formatting. The date is stored in Excel as the dateserial value so should behave correctly when sorting rather than pretending to be a date.
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1");
            HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);

            // handling header.
            foreach (DataColumn column in srcTable.Columns)
                headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);

            //Create date format    
            ICellStyle cellDateStyle = workbook.CreateCellStyle();
            cellDateStyle.DataFormat = workbook.CreateDataFormat().GetFormat("dd/mm/yyyy");

            // handling value.
            int rowIndex = 1;
            foreach (DataRow row in srcTable.Rows)
            {
                HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
                foreach (DataColumn column in srcTable.Columns)
                {
                    if (!System.DBNull.Value.Equals(row[column]) && column.DataType == typeof(DateTime))
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(Convert.ToDateTime(row[column]));
                        dataRow.GetCell(column.Ordinal).CellStyle = cellDateStyle;
                    }
                    else
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                }
                rowIndex++;
            }

Viewing all articles
Browse latest Browse all 1621

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>