1、在导出excel文件时候,默认导出的数字一般都是数值格式,容易形成科学计数法。
所以我们需要在导出的时候将文件设置为文本格式,比较符合需求。
CellStyle css = wb.createCellStyle();
DataFormat format = wb.createDataFormat();
css.setDataFormat(format.getFormat("@"));
cell.setCellStyle(css);
需要这四行代码就可以实现设置文本格式,看一下我导出excel文件的模板
/**
* 没有表头
* @param response
* @param fileName
* @param dataRowList
* @throws Exception
*/
public static void exportExcelNotTitle(HttpServletResponse response, String fileName,
List<?> dataRowList) throws Exception {
int sheetIndex = 0;
final int maxRow = 65000;
final HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
wb.setSheetName(sheetIndex, "Sheet-" + (sheetIndex + 1));
CellStyle css = wb.createCellStyle();
DataFormat format = wb.createDataFormat();
css.setDataFormat(format.getFormat("@"));
int rowNum = 0;
for (final Object dataRow : dataRowList) {
if (rowNum == maxRow) {
sheet = wb.createSheet();
wb.setSheetName(sheetIndex, "Sheet-" + (sheetIndex + 1));
rowNum = 0;
}
HSSFRow row = sheet.createRow(rowNum);
int cellIndex = 0;
Class<?> aClass = dataRow.getClass();
Field[] fields = aClass.getDeclaredFields();
//反射遍历对象所有属性
for (final Field field : fields) {
String name = field.getName();
Method method = aClass.getMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1));
Object data = method.invoke(dataRow);
HSSFCell cell = row.createCell(cellIndex);
Object value = data;
if (value == null) {
value = "";
}
if (value instanceof Date) {
cell.setCellValue(DateUtils.formatDateTime((Date) value, "yyyy-MM-dd HH:mm:ss"));
} else {
cell.setCellValue(value.toString());
}
//设置文本格式
cell.setCellStyle(css);
cellIndex++;
}
rowNum++;
}
wb.write(getExcelOutputStream(response, fileName));
}
public static OutputStream getExcelOutputStream(HttpServletResponse response, String fileName)
throws Exception {
return getOutputStream(response, "application/vnd.ms-excel;charset=utf-8", fileName);
}
public static OutputStream getOutputStream(HttpServletResponse response, String contentType,
String fileName) throws
IOException {
response.setContentType(contentType);
response.setHeader("Content-Disposition",
"attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
return response.getOutputStream();
}
private static HSSFSheet createSheet(HSSFWorkbook wb, int sheetIndex, List<String> titles) {
HSSFSheet sheet = wb.createSheet();
wb.setSheetName(sheetIndex, "Sheet-" + (sheetIndex + 1));
if (titles != null && titles.size() > 0) {
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < titles.size(); ++i) {
final String title = titles.get(i);
HSSFCell cell = row.createCell(i);
cell.setCellValue(title);
}
}
return sheet;
}