How do I set cell value to Date and apply default Excel date format?

前端 未结 6 1701
天涯浪人
天涯浪人 2020-11-29 21:33

I\'ve been using Apache POI for some time to read existing Excel 2003 files programmatically. Now I have a new requirement to create entire .xls files in-memory (still using

6条回答
  •  盖世英雄少女心
    2020-11-29 21:50

    This example is for working with .xlsx file types. This example comes from a .jsp page used to create a .xslx spreadsheet.

    import org.apache.poi.xssf.usermodel.*; //import needed
    
    XSSFWorkbook  wb = new XSSFWorkbook ();  // Create workbook
    XSSFSheet sheet = wb.createSheet();      // Create spreadsheet in workbook
    XSSFRow row = sheet.createRow(rowIndex); // Create the row in the spreadsheet
    
    
    //1. Create the date cell style
    XSSFCreationHelper createHelper = wb.getCreationHelper();
    XSSFCellStyle cellStyle         = wb.createCellStyle();
    cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("MMMM dd, yyyy")); 
    
    //2. Apply the Date cell style to a cell
    
    //This example sets the first cell in the row using the date cell style
    cell = row.createCell(0);
    cell.setCellValue(new Date());
    cell.setCellStyle(cellStyle);
    

提交回复
热议问题