2015-11-11 104 views
6
Cell cell = row.createCell(1); 
    cell.setCellValue(rdf.getEffectiveDate()); 
    cell.getCellStyle().setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy")); 

    cell = row.createCell(2); 
    cell.setCellValue(rdf.getExpiryDate()); 
    cell.getCellStyle().setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy")); 

    row.createCell(3).setCellValue(rdf.getPremium()); 
    row.createCell(4).setCellValue(rdf.getAccountNumber()); 
    row.createCell(5).setCellValue(rdf.getLedgerName()); 

我想在以上兩列中應用日期格式。但它正在適用於所有的細胞。我怎樣才能防止這一點。適用於所有單元格的Apache POI風格

回答

12

正如文檔所述,Cell.getCellStyle()永遠不會返回null。

https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getCellStyle()

當無電池風格的小區被明確設置,然後將返回其最初在工作簿中的所有單元之間共享的默認單元格樣式。然後改變它會明顯影響沒有明確分配風格的所有單元格。

您需要創建一個新的CellStyle,然後將其分配給相關的單元格。

從POI開發指南:

https://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells

Workbook wb = new HSSFWorkbook(); 
    //Workbook wb = new XSSFWorkbook(); 
    CreationHelper createHelper = wb.getCreationHelper(); 
    Sheet sheet = wb.createSheet("new sheet"); 

    // Create a row and put some cells in it. Rows are 0 based. 
    Row row = sheet.createRow(0); 

    // Create a cell and put a date value in it. The first cell is not styled 
    // as a date. 
    Cell cell = row.createCell(0); 
    cell.setCellValue(new Date()); 

    // we style the second cell as a date (and time). It is important to 
    // create a new cell style from the workbook otherwise you can end up 
    // modifying the built in style and effecting not only this cell but other cells. 
    CellStyle cellStyle = wb.createCellStyle(); 
    cellStyle.setDataFormat(
     createHelper.createDataFormat().getFormat("m/d/yy h:mm")); 
    cell = row.createCell(1); 
    cell.setCellValue(new Date()); 
    cell.setCellStyle(cellStyle); 

    //you can also set date as java.util.Calendar 
    cell = row.createCell(2); 
    cell.setCellValue(Calendar.getInstance()); 
    cell.setCellStyle(cellStyle); 

    // Write the output to a file 
    FileOutputStream fileOut = new FileOutputStream("workbook.xls"); 
    wb.write(fileOut); 
    fileOut.close(); 
+0

由於加入。我在此浪費了5小時。你保存了一天。 –

3

嘗試創建一個新的單元格樣式。我想你可能會改變默認風格。因此,像這樣......

CellStyle dateTimeCS = wb.createCellStyle(); 
dateTimeCS.setDataFormat(HSSFDataFormat.getBuiltinFormat("d-mmm-yy")); 
cell.setCellStyle(dateTimeCS); 
相關問題