Java填充Execl模板并返回前端下载

news/2024/7/9 23:59:38 标签: java, 前端, 开发语言, vue

功能:后端使用Java POI填充Execl模板,并返回前端下载

Execl模板如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/b07f29d50c1243d4bdc9919381815a68.png

1. Java后端

功能:填充模板EXECL,并返回前端

controller层

java">package org.huan.controller;

import org.huan.dto.ExcelData;
import org.huan.util.ExcelTemplateFiller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class ExcelController {

    @PostMapping("/generateExcel")
    @ResponseBody
    public ResponseEntity<byte[]> generateExcel(@RequestBody ExcelData excelData) {
        // You'll need to modify the parameters and logic here based on your object and requirements

        // For example:
        String templateFilePath = "C:\\Users\\lenovo\\Desktop\\aa\\a.xlsx";
        String outputFilePath = "C:\\Users\\lenovo\\Desktop\\aa\\output.xlsx";

        // Generate Excel file based on the received object
        ExcelTemplateFiller.execl(templateFilePath, outputFilePath, excelData);

        try {
            // Read the generated file
            Path path = Paths.get(outputFilePath);
            byte[] fileContent = Files.readAllBytes(path);

            // Create a ResponseEntity with the file content as body
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            headers.setContentDispositionFormData("attachment", "output.xlsx");
            headers.setContentLength(fileContent.length);

            return ResponseEntity.ok().headers(headers).body(fileContent);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(null);
        }
    }
}


ExcelTemplateFiller POI填充表格

java">package org.huan.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.huan.dto.ExcelData;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ExcelTemplateFiller {

    public static void main(String[] args) {
        String templateFilePath = "C:\\Users\\lenovo\\Desktop\\aa\\a.xlsx";
        String outputFilePath = "C:\\Users\\lenovo\\Desktop\\aa\\output.xlsx";
        //execl(templateFilePath, outputFilePath);
    }

    public static void execl(String templateFilePath, String outputFilePath, ExcelData excelData) {

        try (InputStream templateInputStream = Files.newInputStream(Paths.get(templateFilePath));
             Workbook workbook = new XSSFWorkbook(templateInputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            
            //全 称
            sheet.getRow(8).getCell(27).setCellValue(excelData.getFullName());
            //账号
            sheet.getRow(10).getCell(27).setCellValue(excelData.getAccountNumber());
            //开户机构
            sheet.getRow(12).getCell(27).setCellValue(excelData.getAccountInstitution());
            //人民币(大写)
            sheet.getRow(14).getCell(7).setCellValue(excelData.getRmbInWords());

            //十 亿 千 百 十 万 千 百 十 元 角 分
            // 十亿, 亿, 千万, 百万, 十万, 万, 千, 百, 十, 元, 角, 分
            Row row = sheet.getRow(15);
            row.getCell(30).setCellValue(excelData.getBillion());
            row.getCell(31).setCellValue(excelData.getHundredMillion());
            row.getCell(32).setCellValue(excelData.getTenMillion());
            row.getCell(33).setCellValue(excelData.getMillion());
            row.getCell(34).setCellValue(excelData.getHundredThousand());
            row.getCell(35).setCellValue(excelData.getTenThousand());
            row.getCell(36).setCellValue(excelData.getThousand());
            row.getCell(37).setCellValue(excelData.getHundred());
            row.getCell(38).setCellValue(excelData.getTen());
            row.getCell(39).setCellValue(excelData.getYuan());
            row.getCell(40).setCellValue(excelData.getJiao());
            row.getCell(41).setCellValue(excelData.getFen());

            //用途
            sheet.getRow(16).getCell(7).setCellValue(excelData.getPurpose());
            //备注
            sheet.getRow(17).getCell(7).setCellValue(excelData.getRemark());
            try (FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath)) {
                workbook.write(fileOutputStream);
            }
            System.out.println("Data has been filled into the Excel template successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

实体类

java">package org.huan.dto;

import lombok.Data;

@Data
public class ExcelData {
    private String fullName;
    private String accountNumber;
    private String accountInstitution;
    private String rmbInWords;

    private String billion;
    private String hundredMillion;
    private String tenMillion;
    private String million;
    private String hundredThousand;
    private String tenThousand;
    private String thousand;
    private String hundred;
    private String ten;
    private String yuan;
    private String jiao;
    private String fen;

    private String purpose;
    private String remark;

}

pom依赖

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.14</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>3.14</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-scratchpad</artifactId>
      <version>3.14</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.14</version>
    </dependency>

2. VUE前端

功能:
2.1 利用Vue过滤器实现 Vue数字金额转大写
2.2 点击按钮下载后端 EXECl



<span>{{model.balance | toChies(amount)}}</span>
<template>
  <div>
    <button @click="downloadExcel">Download Excel</button>
  </div>
</template>

<script>javascript">
export default {
  data() {
    return {
     excelData: {
        fullName: 'John Doe',
        accountNumber: '1234567890',
        accountInstitution: 'ABC Bank',
        rmbInWords: 'One Thousand Yuan',
        billion: '1',
        hundredMillion: '1',
        tenMillion: '1',
        million: '1',
        hundredThousand: '1',
        tenThousand: '1',
        thousand: '1',
        hundred: '1',
        ten: '1',
        yuan: '1',
        jiao: '1',
        fen: '1',
        purpose: 'Purchase',
        remark: 'No remarks',
      },
    };
    };
  },

filters:{
  toChies(amount){
    // 汉字的数字
    const cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
    // 基本单位
    const cnIntRadice = ["", "拾", "佰", "仟"];
    // 对应整数部分扩展单位
    const cnIntUnits = ["", "万", "亿", "兆"];
    // 对应小数部分单位
    const cnDecUnits = ["角", "分"];
    // 整数金额时后面跟的字符
    const cnInteger = "整";
    // 整型完以后的单位
    const cnIntLast = "元";
    // 最大处理的数字
    const maxNum = 9999999999999999.99;
    // 金额整数部分
    let integerNum;
    // 金额小数部分
    let decimalNum;
    // 输出的中文金额字符串
    let chineseStr = "";
    // 分离金额后用的数组,预定义
    let parts;
    if (amount === "") {
      return "";
    }
    amount = parseFloat(amount);
    if (amount >= maxNum) {
      // 超出最大处理数字
      return "";
    }
    if (amount === 0) {
      chineseStr = cnNums[0] + cnIntLast + cnInteger;
      return chineseStr;
    }
    // 转换为字符串
    amount = amount.toString();
    if (amount.indexOf(".") === -1) {
      integerNum = amount;

      decimalNum = "";
    } else {
      parts = amount.split(".");
      integerNum = parts[0];
      decimalNum = parts[1].substr(0, 4);
    }
    // 获取整型部分转换
    if (parseInt(integerNum, 10) > 0) {
      let zeroCount = 0;
      const IntLen = integerNum.length;
      for (let i = 0; i < IntLen; i++) {
        const n = integerNum.substr(i, 1);
        const p = IntLen - i - 1;
        const q = p / 4;
        const m = p % 4;
        if (n === "0") {
          zeroCount++;
        } else {
          if (zeroCount > 0) {
            chineseStr += cnNums[0];
          }
          // 归零
          zeroCount = 0;
          //alert(cnNums[parseInt(n)])
          chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
        }
        if (m === 0 && zeroCount < 4) {
          chineseStr += cnIntUnits[q];
        }
      }
      chineseStr += cnIntLast;
    }
    // 小数部分
    if (decimalNum !== "") {
      const decLen = decimalNum.length;
      for (let i = 0; i < decLen; i++) {
        const n = decimalNum.substr(i, 1);
        if (n !== "0") {
          chineseStr += cnNums[Number(n)] + cnDecUnits[i];
        }
      }
    }
    if (chineseStr === "") {
      chineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (decimalNum === "") {
      chineseStr += cnInteger;
    }
    return chineseStr;
  }
},

 
  methods: {
		const formattedAmount = this.$options.filters.toChies(this.excelData.rmbInWords);
		 downloadExcel() {
 		  this.excelData = { rmbInWords: formattedAmount ...};
	      axios({
	        url: 'http://your-backend-url/generateExcel', // Replace with your backend endpoint
	        method: 'POST',
	        responseType: 'blob', // Specify response type as blob to handle binary data
	        data: this.excelData,
	      })
	        .then((response) => {
	          const url = window.URL.createObjectURL(new Blob([response.data]));
	          const link = document.createElement('a');
	          link.href = url;
	          link.setAttribute('download', 'output.xlsx'); // Set the file name here
	          document.body.appendChild(link);
	          link.click();
	        })
	        .catch((error) => {
	          console.error('Error downloading Excel:', error);
	        });
	    },
};

</script>


http://www.niftyadmin.cn/n/5318754.html

相关文章

Android Gradle Plugin、Gradle、Android Studio版本关系

参考链接 Android Gradle Plugin 与 gradle 对应关系 插件版本所需的最低 Gradle 版本8.38.48.28.28.18.08.08.07.47.57.37.47.27.3.37.17.27.07.04.2.06.7.14.1.06.54.0.06.1.13.6.0 - 3.6.45.6.43.5.0 - 3.5.45.4.13.4.0 - 3.4.35.1.13.3.0 - 3.3.34.10.13.2.0 - 3.2.14.63…

test Symbolic Execution-01-符号执行(Symbolic Execution)简介

拓展阅读 开源 Auto generate mock data for java test.(便于 Java 测试自动生成对象信息) 开源 Junit performance rely on junit5 and jdk8.(java 性能测试框架。性能测试。压测。测试报告生成。) test fuzz-01-模糊测试&#xff08;Fuzz Testing&#xff09; 详细介绍测…

Unity对应SDK和NDK版本的对照表

官网&#xff1a;Unity - Manual: Android environment setup 本人安装的是2022版本长期支持版本2022.3.15f1c1 安装Java的JDK环境就不在这里展开了&#xff0c;就记录下对Android SDK的设置&#xff0c;要与Unity的版本对应&#xff0c;否则会出现很多莫名奇妙的问题。 打开…

Dubbo 框架揭秘:分布式架构的精髓与魔法【一】

欢迎来到我的博客&#xff0c;代码的世界里&#xff0c;每一行都是一个故事 Dubbo 框架揭秘&#xff1a;分布式架构的精髓与魔法【一】 前言Dubbo是什么Dubbo的核心概念整体设计 前言 在数字时代&#xff0c;分布式架构正成为应对大规模流量和复杂业务场景的标配。Dubbo&#…

Elasticsearch:Search tutorial - 使用 Python 进行搜索 (三)

这个是继上一篇文章 “Elasticsearch&#xff1a;Serarch tutorial - 使用 Python 进行搜索 &#xff08;二&#xff09;” 的续篇。在今天的文章中&#xff0c;本节将向你介绍一种不同的搜索方式&#xff0c;利用机器学习 (ML) 技术来解释含义和上下文。 向量搜索 嵌入 (embed…

启动Spring Boot+vue前后端分离的若依(RuoYi)项目

下载若依项目&#xff1a;RuoYi-Vue: &#x1f389; 基于SpringBoot&#xff0c;Spring Security&#xff0c;JWT&#xff0c;Vue & Element 的前后端分离权限管理系统&#xff0c;同时提供了 Vue3 的版本 (gitee.com) 下载好的项目目录结构 这是前端项目&#xff0c;其余…

了解PyTorch中的缩放点积注意力及演示

torch.nn.functional.scaled_dot_product_attention 函数在 PyTorch 框架中用于实现缩放点积注意力&#xff08;Scaled Dot-Product Attention&#xff09;。这是一种在自然语言处理和计算机视觉等领域常用的注意力机制。它的主要目的是通过计算查询&#xff08;query&#xff…

C语言程序由哪些部分组成?

一、问题 一个C语言程序都由哪些部分组成? 它的基本单位是什么? 二、解答 一个 C语言程序可以由一个主函数和若干个函数构成。一个大的应用程序一般应该分为多个程序模块&#xff0c;每一个模块用来实现一个功能。实现这些模块功能的可以叫做子程序。 在 C 语言中&#xff…