使用POI读取EXCEL模板并填充数据,上传至腾讯云储存桶


前言

有时候我们可能需要做一个EXCEL表格样式的个人电子档案,那么一行数据一行数据设值填充需要很麻烦的计算与操作。这时候我们就可以读取一个模板,简单的填空就可以了,最后生成一个新的EXCEL文件来满足我们的需要


一、POI导入

这个不多说,全靠这个依赖活下来的,重中之重

<!-- POI EXCEL 文件读写 -->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
   <dependency>
       <groupId>org.apache.poi</groupId>
       <artifactId>poi</artifactId>
       <version>4.1.2</version>
   </dependency>
   <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant -->
   <dependency>
       <groupId>org.apache.poi</groupId>
       <artifactId>poi-excelant</artifactId>
       <version>4.1.2</version>
   </dependency>
   <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
   <dependency>
       <groupId>org.apache.poi</groupId>
       <artifactId>poi-ooxml</artifactId>
       <version>4.1.2</version>
   </dependency>
   <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
   <dependency>
       <groupId>org.apache.poi</groupId>
       <artifactId>poi-ooxml-schemas</artifactId>
       <version>4.1.2</version>
   </dependency>
   <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
   <dependency>
       <groupId>org.apache.poi</groupId>
       <artifactId>poi-scratchpad</artifactId>
       <version>4.1.2</version>
   </dependency>

二、具体实现

1.制作我们的模板

这个大家都会做吧,做的如何要看你的审美喽

在这里插入图片描述
emmmm… 测试用,所以做的很简单(我审美不行的😐)

我在需要填充的数据那里用索引来代替数据,方便到时候填充数据,对应表格嘛,所以第二行第二列那里就是1,1,其实这样也方便你设置居中之类的样式

2.读取模板来生成新的EXCEL

具体不懂的可以看注释哦😏:

	public static void createEmpExcel(Map<String, Object> emp01) throws IOException{
        // import為需要導入的EXCEL模板,exportFilePath為生成的員工EXCEL文件
        String importFilePath = "src/main/resources/static/excelTemp/empTemplate.xlsx";
        String exportFilePath = "src/main/resources/static/excelFile/emp01.xlsx";
        BufferedImage bufferImg = null;

        File fi = new File(importFilePath);
        InputStream in = new FileInputStream(fi);
        //读取excel模板
        XSSFWorkbook wb = new XSSFWorkbook(in);
        //读取了模板内所有sheet内容
        XSSFSheet sheet = wb.getSheetAt(0);
        //如果这行没有了,整个公式都不会有自动计算的效果的
        sheet.setForceFormulaRecalculation(true);

        // 把照片設置進EXCEl中
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        // 讀取照片
        bufferImg = ImageIO.read(new File("src/main/resources/static/excelTemp/emp01.png"));
        ImageIO.write(bufferImg, "png", byteArrayOut);
        XSSFDrawing patriarch = sheet.createDrawingPatriarch();
        // 設置圖片位置,左上角2,6    右下角5,8
        XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 255, 255, (short) 6, 2, (short) 8, 5);
        // anchor主要用于设置图片的属性
        anchor.setAnchorType(ClientAnchor.AnchorType.byId(3));
        // 插入图片
        patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

        /*
            1,1 編號  empNumber
            1,4 入職日期    empAddDate
            2,1 姓名  empName
            2,3 性別  empSex
            2,5 民族  empNation
            3,1 政治面貌    empPolicita
            3,3 出生日期    empBirthday
            4,1 手機號 empPhone
            4,3 身份證 empIdCard
            5,2 所屬單位    empOrgName
            6,2 現居住地    empNowAddress
            7,2 戶籍地址    empAddress

         */
        // 給模板設置員工的信息
        sheet.getRow(1).getCell(1).setCellValue(emp01.get("empNumber").toString());
        sheet.getRow(1).getCell(4).setCellValue(emp01.get("empAddDate").toString());
        sheet.getRow(2).getCell(1).setCellValue(emp01.get("empName").toString());
        sheet.getRow(2).getCell(3).setCellValue((int) emp01.get("empSex") == 1 ? "男" : "女");
        sheet.getRow(2).getCell(5).setCellValue(emp01.get("empNation").toString());
        sheet.getRow(3).getCell(1).setCellValue(emp01.get("empPolicita").toString());
        sheet.getRow(3).getCell(3).setCellValue(emp01.get("empBirthday").toString());
        sheet.getRow(4).getCell(1).setCellValue(emp01.get("empPhone").toString());
        sheet.getRow(4).getCell(3).setCellValue(emp01.get("empIdCard").toString());
        sheet.getRow(5).getCell(2).setCellValue(emp01.get("empOrgName").toString());
        sheet.getRow(6).getCell(2).setCellValue(emp01.get("empNowAddress").toString());
        sheet.getRow(7).getCell(2).setCellValue(emp01.get("empAddress").toString());
        FileOutputStream out = new FileOutputStream(exportFilePath);
        wb.write(out);
        out.close();
    }

然后我们模拟一个Map数据,调用一下方法来生成一个模板

	public static void main(String[] args) throws IOException {

        // 模擬員工個人信息
        Map<String, Object> emp01 = new HashMap<>();
        emp01.put("empAddDate", "2020-10-10");
        emp01.put("empNumber", "20201001");
        emp01.put("empName", "金木");
        emp01.put("empSex", 1);
        emp01.put("empNation", "漢族");
        emp01.put("empPolicita", "群衆");
        emp01.put("empBirthday", "1999-12-07");
        emp01.put("empPhone", "10010");
        emp01.put("empIdCard", "410426xxxxxxxxxxxx");
        emp01.put("empOrgName", "青桐樹");
        emp01.put("empNowAddress", "上海市xxxxxx");
        emp01.put("empAddress", "北京市xxxxxx");

        // 讀取模板生成員工個人檔案文件
        createEmpExcel(emp01);

        // 存入騰訊雲儲存桶
        // uploadEmpExcel(emp01.get("empName").toString());

    }

3.查看生成结果

这个是模板文件,图片文件,以及新的EXCEL文件目录
在这里插入图片描述
好了,一一对应,然后看一下这个emp01.xlsx内容

在这里插入图片描述

预览后看起来还不错,这就算完成了,给大家说个打印机,Zan,可以模拟图像打印还不错

三,传到腾讯云储存桶里

看完你就全会了:COS对象储存API文档.

其实你可以传到很多地方,我觉得储存通单个上传文件还是挺简单的,所以我们来看一下代码吧

1.导入COS依赖

这个是官方给的pom依赖,然后我加了个可以把名字转字母的依赖随便试一下

<!-- Tencent Cloud COS -->
<dependency>
    <groupId>com.qcloud</groupId>
    <artifactId>cos_api</artifactId>
    <version>5.6.24</version>
</dependency>
<!-- 拼音转字母 -->
<dependency>
    <groupId>com.belerweb</groupId>
    <artifactId>pinyin4j</artifactId>
    <version>2.5.0</version>
</dependency>

2.写个工具类

CV一下COS储存桶的API文档代码就OK了,这里面有个MultipartFile转File的方式,是为了方便控制类接受MultipartFile后进行操作的

package cn.liu783.vueappjava.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class UploadTCloudUtil {

    // 1 初始化用户身份信息(secretId, secretKey)
    static COSCredentials cred = new BasicCOSCredentials(
            "COS_SECRETID",
            "COS_SECRETKEY");
    // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
    static ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
    // 3 生成cos客户端
    static COSClient cosClient = new COSClient(cred, clientConfig);
    // bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
    static String bucketName = "xxxx-6666666666";

    // 将本地文件上传到 COS
    public static String uploadFile(String key01, File file) {
        PutObjectResult putObjectResult = cosClient.putObject(bucketName, key01, file);
        return putObjectResult.getETag();
    }

    // 下載文件至本地
    public static void downloadFile(String key01){
        String key = "exampleobject";
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        String outputFilePath = "src/main/resources/static/excelFile/emp01.xlsx";
        File downFile = new File(outputFilePath);
        getObjectRequest = new GetObjectRequest(bucketName, key01);
        ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);
    }

    // 传入要删除的key
    public static void deleteFile(String key01){
        cosClient.deleteObject(bucketName, key01);
    }

    // MultipartFile轉換為File
    public static File MultipartFileToFile(MultipartFile file, String saveOldPath) {
        File f = null;
        try {
            InputStream is = file.getInputStream();
            f = new File(saveOldPath);
            OutputStream os = new FileOutputStream(f);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f;
    }

}

3.调用代码上传并读取

在这里我把"金木"当成参数传了进去,然后生成JM.xlsx新的文件名(其实没啥用,实际中都是加密文件名)
savePath其实就是你储存桶里的文件夹路径而已
我这里用了传File类型的方式上传的,很便捷,COS也支持输入流的方式上传

	public static String uploadEmpExcel(String empName) {
        File file = new File("src/main/resources/static/excelFile/emp01.xlsx");
        String name = file.getName();
        String suffix = name.substring(name.lastIndexOf("."));
        String newFileName = SpellHelper.getFirstPinYin(empName) + suffix;
        System.out.println(newFileName);
        String savePath = "hnccms/excel/test/" + newFileName;
        return UploadTCloudUtil.uploadFile(savePath, file);
    }

现在云上就有了,然后你就可以访问下载了

在这里插入图片描述

四,生成自定义XLSX模板

1.主要代码

	// 生成模板01
	public static void createTemp01() throws Exception {
	    try {
	        // 创建工作表以及吉字体大小和居中样式
	        HSSFWorkbook workbook = new HSSFWorkbook();
	        HSSFSheet sheet = workbook.createSheet("员工信息");
	        HSSFCellStyle style = getStyle(workbook);
	
	        // 设置8个列宽,最后两列宽度小一点
	        for (int i = 0; i < 8; i++) {
	            sheet.setColumnWidth(i,256 * 12);
	            if (i == 6 || i == 7)
	                sheet.setColumnWidth(i, 256 * 8);
	        }
	
	        /**
	         * 合并单元格,add一个MergedRegion就合并一个区域,索引从0开始
	         * firstRow: 从哪行开始
	         * lastRow: 到哪行结束
	         * firstCol: 从哪列开始
	         * lastCol: 到哪列结束
	         */
	        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
	        sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
	        sheet.addMergedRegion(new CellRangeAddress(1, 1, 4, 7));
	        sheet.addMergedRegion(new CellRangeAddress(2, 4, 6, 7));
	
	        // Row 1 创建第一行
	        HSSFRow rowTitle = sheet.createRow(0);
	        rowTitle.setHeight((short)(35*20));
	        HSSFCell cellTitle = rowTitle.createCell(0);
	        cellTitle.setCellStyle(style);
	        cellTitle.setCellValue("员工信息表");
	
	        // Row 2 创建第二行
	        HSSFRow rowTwo = sheet.createRow(1);
	        rowTwo.setHeight((short)(40*20));
	        // 编号标题
	        HSSFCell cellTwo1 = rowTwo.createCell(0);
	        cellTwo1.setCellStyle(style);
	        cellTwo1.setCellValue("编号");
	        // 编号值,也可以不创建单元格,默认空
	        HSSFCell cellTwo2 = rowTwo.createCell(1);
	        cellTwo2.setCellValue("");
	        // 日期标题
	        HSSFCell cellTwo3 = rowTwo.createCell(3);
	        cellTwo3.setCellStyle(style);
	        cellTwo3.setCellValue("日期");
	        // 日期值
	        HSSFCell cellTwo4 = rowTwo.createCell(4);
	        cellTwo4.setCellValue("");
	
	        // Row 3 创建第三行
	        HSSFRow rowThree = sheet.createRow(2);
	        rowThree.setHeight((short)(40*20));
	        // 编号
	        HSSFCell cellThree1 = rowThree.createCell(0);
	        cellThree1.setCellStyle(style);
	        cellThree1.setCellValue("姓名");
	        // 日期
	        HSSFCell cellThree2 = rowThree.createCell(2);
	        cellThree2.setCellStyle(style);
	        cellThree2.setCellValue("性别");
	        // 日期
	        HSSFCell cellThree3 = rowThree.createCell(4);
	        cellThree3.setCellStyle(style);
	        cellThree3.setCellValue("民族");
	
	        // Row 4
	        HSSFRow rowFour = sheet.createRow(3);
	        rowFour.setHeight((short)(40*20));
	
	        // Row 5
	        HSSFRow rowFive = sheet.createRow(4);
	        rowFive.setHeight((short)(40*20));
	
	        if (workbook != null) {
	            try {
	                // 导出
	                FileOutputStream fileOut = new FileOutputStream("D:\\员工信息模板.xls");
	                workbook.write(fileOut);
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
	    } catch (Exception e) { }
	}
	
	// 单元格样式
	public static HSSFCellStyle getStyle(HSSFWorkbook workbook) {
	    // 设置字体
	    HSSFFont font = workbook.createFont();
	    // 设置字体大小
	    font.setFontHeightInPoints((short) 12);
	    // 设置字体名字
	    font.setFontName("Courier New");
	    // 设置样式;
	    HSSFCellStyle style = workbook.createCellStyle();
	    // 在样式用应用设置的字体;
	    style.setFont(font);
	    // 设置自动换行;
	    style.setWrapText(false);
	    // 设置水平对齐的样式为居中对齐;
	    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	    // 设置垂直对齐的样式为居中对齐;
	    style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
	    return style;
	}
	
	public static void main(String[] args) throws Exception {
	   createTemp01();
	}

2.结果

简单创建几行看下效果,主要还是合并做好了就差不多

在这里插入图片描述

3.注意事项

  • 生产模板逻辑复杂,比手动修改XLSX文件难上加难
  • 无法灵活扩展,实际项目模板样式文件千变万化
  • 效果略差,不能随意自定义单个区域背景色和边框

总结

以上就是如何读取EXCEL模板然后生成新的EXCEL文件了,我们可以根据我们不同的需要做很多档案模板。之后我会写一篇读取云上的EXCEL预览下载的文章,感谢大家费时观看啦

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值