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); } } } }