java POI生成excel设置列格式并写入文件 SpringBoot项目

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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值