1. 程式人生 > 實用技巧 >poi匯出excel保留原始格式

poi匯出excel保留原始格式

1.設定通用方法全部轉換為String,但有的客戶需要保留原始型別

程式碼改造如下:

/**
* 按照格式方案的配置匯出資料
* @param formattor 格式
* @param formatType 格式化型別
* @param value 原始資料
* @param cell 當前單元格
*/
private void formatData(String formattor, FormatType formatType, String value, Cell cell) {
if (formattor != null && formattor.length() > 0 ) {
CellStyle cellStyle = cell.getCellStyle();
XSSFDataFormat df = _excelWorkBook.createDataFormat(); //此處設定資料格式
cellStyle.setDataFormat(df.getFormat(formattor)); // 基於傳遞的格式設定單元格
if (formatType == FormatType.DateTime ) {
if (value != null && value.length() != 0) {
SimpleDateFormat format = new SimpleDateFormat(dateSet(value));
Date d = null;
try {
//生成時間物件
d = format.parse(value);
} catch (Exception e) {
throw new QORuntimeException(null, ExceptionCodes.ExcelExport, e);
}
cell.setCellValue(d);
} else {
cell.setCellValue("");
}
} else if (formatType == FormatType.Number) {
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(Double.parseDouble(value));
} else if (formatType == FormatType.Logic) {
String[] keys = formattor.split(";")[0].split("/");
String[] values = formattor.split(";")[1].split("/");
for (int i = 0; i < keys.length; i++) {
if (value.equals(keys[i])) {
value = values[i];
}
}
cell.setCellValue(Double.parseDouble(value));
}
} else{
cell.setCellValue(value);
}
}