2016-07-04 36 views
1

我正在閱讀excel,這似乎有user defined data formats。 例如,它有一個數據格式:"yyyy"E,這只是顯示後跟字母E.POI-XSSF:用戶定義的數據格式

yyyy格式的日期現在,這種格式是不是內置的,可用的格式的一部分。

因此,似乎當我嘗試將其設置爲CellStyleDataFormat時,它不起作用。

首先我讀了一個工作簿,然後從這個工作簿中創建DataFormat

XSSFWorkbook wb = new XSSFWorkbook(excelToRead); 
XSSFDataFormat df = wb.createDataFormat(); 

df對象現在具有user defined data formats以及(通過印刷,直到200選中)。 現在,我嘗試創建在同一工作簿中的新小區,有一個新的風格是這樣的:

XSSFCell cellTemp = row.createCell(0); 
XSSFCellStyle styleTemp = wb.createCellStyle(); 
styleTemp.setDataFormat(df.getFormat(cell.getCellStyle().getDataFormatString())); 
cellTemp.setCellStyle(styleTemp); 
cellTemp.setCellValue(cell.getStringCellValue()); 
System.out.print(formatter.formatCellValue(cellTemp)+" "); 

但是,格式不給我正確的字符串值,而不是它給我的基本的整數值的日期(如果格式不被識別,我猜是默認的)。

在XSSF中使用用戶定義格式的正確方法是什麼?

UPDATE:看來,我能夠使用其它用戶定義的格式,如yyyy0.0%但不yyyy"E"yyyy"A"

回答

0

這是不是真的清楚我究竟你要實現的目標。但是,如果DataFormatter格式不正確,那麼也可以使用從 CellFormatter派生的類。

例子:

import java.io.*; 

import org.apache.poi.ss.usermodel.*; 
import org.apache.poi.ss.format.*; 
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 

import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

import java.awt.Desktop; 
import java.util.Date; 

class CustomDateFormatTest { 

public static void main(String[] args) { 
    try { 

    Workbook wb = new XSSFWorkbook(); 
    Sheet sheet = wb.createSheet("Sheet1"); 
    Row row = sheet.createRow(0); 
    Cell cell = row.createCell(0); 

    cell.setCellValue(new Date()); 

    DataFormat format = wb.createDataFormat(); 
    CellStyle cellstyle = wb.createCellStyle(); 
    cellstyle.setDataFormat(format.getFormat("yyyy\"E\"")); 

    cell.setCellStyle(cellstyle); 

    OutputStream out = new FileOutputStream("CustomDateFormatTest.xlsx"); 
    wb.write(out); 
    wb.close(); 

    System.out.println("Done"); 
    File outputfile = new File("CustomDateFormatTest.xlsx"); 
    Desktop.getDesktop().open(outputfile); 

    InputStream inp = new FileInputStream("CustomDateFormatTest.xlsx"); 
    wb = WorkbookFactory.create(inp); 

    sheet = wb.getSheetAt(0); 
    row = sheet.getRow(0); 
    cell = row.getCell(0); 

    //This will not format properly 
    DataFormatter dataformatter = new DataFormatter(); 
    System.out.println(dataformatter.formatCellValue(cell)); 

    //This will format properly 
    String formatstring = cell.getCellStyle().getDataFormatString(); 
    System.out.println(formatstring); 
    CellDateFormatter celldateformatter = new CellDateFormatter(formatstring); 
    //For using CellDateFormatter we need to know that the cell value is a Date. 
    System.out.println(celldateformatter.format(cell.getDateCellValue())); 


    } catch (InvalidFormatException ifex) { 
    } catch (FileNotFoundException fnfex) { 
    } catch (IOException ioex) { 
    } 
} 
} 
+0

這實際上工作!非常感謝...你有什麼想法爲什麼其他用戶格式工作,但這(yyyy「E」)之一沒有? – gaurav5430

相關問題