java使用POI下載導入模板,常常會因爲自帶的格式爲常規,導致導入的數據型內容,默認帶四位小數,或者超過12位後使用科學計數型表示,但是服務器又需要驗證數據的準確性,所以往往很難校驗數據的準確性,用戶輸入也很麻煩,爲了解決此種情況發生,往往給模板的默認格式爲文本格式,這樣就可以無視用戶的輸入,能夠更好的校驗內容,下面是使用java將Excel格式設置成文本的方法
/** * @desc 設置excel文本格式 * @param targetWorkbook * @param targetSheet * @param startRow * @param startColumn * @param endRow * @param endColumn */ public static void setColumnToTextFormat(XSSFWorkbook targetWorkbook, XSSFSheet targetSheet, int startRow, int startColumn, int endRow, int endColumn){ XSSFCellStyle cellStyle = targetWorkbook.createCellStyle(); XSSFDataFormat format = targetWorkbook.createDataFormat(); cellStyle.setDataFormat(format.getFormat("@")); if(startRow <0 || endRow <0 || startColumn <0 || endColumn <0 || (startRow > endRow) || (startColumn > endColumn)){ throw new ApplicationException("生成Excel格式參數錯誤!"); } for(int rowIndex = startRow ; rowIndex <= endRow ; rowIndex ++ ){ XSSFRow row = targetSheet.getRow(rowIndex); if(row == null ) { row = targetSheet.createRow(rowIndex); } for (int columnIndex = startColumn ; columnIndex <= endColumn ; columnIndex ++ ){ XSSFCell cell = row.getCell(columnIndex); if (cell == null){ cell = row.createCell(columnIndex); } String rawValue1 = cell.getRawValue(); cell.setCellStyle(cellStyle); if(StringUtil.isNotBlank(rawValue1)){ cell.setCellValue(rawValue1); } } } }