java POI生成excel设置列格式并写入文件 SpringBoot项目
改变数据后,删除原来的附件(文件),生成一个新的格式的excel文件并通过数据类型设置这一类的数据格式数字或者日期等等
简单粗暴的直接上代码吧
ImportSettingColumns是项目中的对象 请给我自行更换一下吧
//生成excel文档
public Workbook generateExcel(List<ImportSettingColumns> importSettingColumnsListHeader){
//创建excel文档对象
Workbook workbook = new HSSFWorkbook();
//创建excel表单
Sheet sheet = workbook.createSheet();
//写入excel表格头
writeExcelHeader(sheet, importSettingColumnsListHeader,workbook);
return workbook;
}
//写入表头以及该列的文本格式
private void writeExcelHeader(Sheet sheet, List<ImportSettingColumns> importSettingColumnsListHeader,Workbook workbook) {
// Object[] keys = header.keySet().toArray();
// sheet.setDefaultColumnStyle(0, css);//设置第0列为文本格式
//日期的格式
CellStyle hssfCellStyleDate = workbook.createCellStyle();
DataFormat df = workbook.createDataFormat(); // 此处设置数据格式
hssfCellStyleDate.setDataFormat(df.getFormat("yyyy-MM-dd"));
//数字格式保留两位小数
CellStyle cellStyleNum = workbook.createCellStyle();
cellStyleNum.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
Row row = sheet.createRow(0);
int len = importSettingColumnsListHeader.size();
for (int i = 0; i < len; i++) {
String[] str = importSettingColumnsListHeader.get(i).getDataType().split("\\.");
if (str.length > 1 && str[str.length-1].equals("Date")){
sheet.setDefaultColumnStyle(i,hssfCellStyleDate);//设置该列的格式
}
// else if (str.length > 1 && str[str.length-1].equals("Double")){
// sheet.setDefaultColumnStyle(i,cellStyleNum);
// }
Cell cell = row.createCell(i);
String hearText = importSettingColumnsListHeader.get(i).getColumnImportName();
cell.setCellValue(hearText);
}
}
//生成excel文件名称
String fileString = generateSuffix()+importSetting.getName()+".xls";
try {
FileOutputStream output=new FileOutputStream(new File(Config.uploadFileAddress + "/" + ymd + "/" +fileString));
workbook.write(output);//写入磁盘
output.close();
} catch (IOException e) {
e.printStackTrace();
}
public static String generateSuffix() {
// 获得当前时间
DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
// 转换为字符串
String formatDate = format.format(new Date());
// 随机生成文件编号
int random = new Random().nextInt(10000);
return new StringBuffer().append(formatDate).append(
random).toString();
}