Java操作xls替换文本或图片的功能实现

2024-12-30 15:50

本文主要是介绍Java操作xls替换文本或图片的功能实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Java操作xls替换文本或图片的功能实现》这篇文章主要给大家介绍了关于Java操作xls替换文本或图片功能实现的相关资料,文中通过示例代码讲解了文件上传、文件处理和Excel文件生成,需要的朋友可...

准备xls编程模板文件:template.xls

Java操作xls替换文本或图片的功能实现

要求根据不同的产品型号和图片,插入到模板文件中,然后再填充产品信息。

准备需要替换的图片和数据

Java操作xls替换文本或图片的功能实现

功能实现

 定义了一个名为BaseProductController的RESTful控制器,它负责处理与成品管理相关的HTTP请求。该控制器使用了Spring框架、Swagger注解以及Apache POI库来处理文件上传和Excel文档生成。

包声明与导入

package net.work.controller.base;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.worChina编程k.request.base.BaseProductReq;
import net.work.request.base.ProductExcelReq;
import net.work.service.base.BaseProductService;
import net.work.util.jsonData;
import net.work.util.StoreUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import Javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
  • 包声明:指定了类所在的包路径。
  • 导入:引入了必要的类和接口,包括Swagger注解、自定义请求对象和服务接口、工具类、Apache POI库、Spring框架注解等。

类声明与注解

@RefreshScope
@Api(tags = "成品管理")
@RestController
@RequestMapping("/api/base/v1/product/")
public class BaseProductController {
  • @RefreshScope:允许在运行时刷新配置属性,适用于Spring Cloud环境中的动态配置更新。
  • @Api(tags = "成品管理"):Swagger注解,用于标记此控制器属于“成品管理”模块,以便在API文档中分类。
  • @RestController:Spring MVC注解,表明这是一个RESTful风格的控制器,返回的数据将直接写入HTTP响应体中。
  • @RequestMapping("/api/base/v1/product/"):指定该控制器下的所有端点的基础URL路径为/api/base/v1/product/

注入依赖与配置属性

@Value("${product.filePath}")
private String filePath;

@Autowired
private BaseProductService baseProductService;
  • @Value("${product.filePath}"):从外部化配置文件中读取产品文件路径,并注入到filePath字段。
  • @Autowired:自动注入BaseProductService服务实例,用于处理业务逻辑。

方法解析

产品尺寸图和接线图导入

@ApiOperation("产品尺寸图和接线图导入")
@PostMapping("importProductImage")
public JsonData importProductImage(@RequestParam("file") MultipartFile file, String productModel) throws Exception {
    return baseProductService.importProductImage(file, filePath, productModel);
}
  • importProductImage:处理产品尺寸图和接线图的上传。
    • 使用@PostMapping注解指定这是POST请求处理方法。
    • @RequestParam("file")获取上传的文件,String productModel获取产品型号。
    • 调用baseProductService.importProductImage方法进行实际的文件处理,并返回处理结果作为JSON数据。

创建产品规格书xlsx

@ApiOperation("创建产品规格书xlsx")
@PostMapping("createProductExcel")
public void createProductExcel(@RequestBody ProductExcelReq productExcelReq) throws Exception {
    String productModel = productExcelReq.getProductModel();
    File file1 = new File(filePath + productModel + "\\img1.png");
    if (!file1.exists()) {
        throw new Exception("当前产品型号【" + productModel + "】img1.png文件不存在!");
    }
    File file2 = new File(filePath + productModel + "\\img2.png");
    if (!file2.exists()) {
        throw new Exception("当前产品型号【" + productModel + "】img2.png文件不存在!");
    }

    InputStream inputStream1 = new FileInputStream(file1);
    InputStream inputStream2 = new FileInputStream(file2);

    Workbook workbook = StoreUtil.createProductExcel(filePath, inputStream1, inputStream2, productExcelReq);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    workbook.write(outputStream);
    workbook.close();

    HttpServletResponse response = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getResponse();
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "atta编程chment;filename=" + productExcelReq.getProductModel() + ".xlsx");

    OutputStream out = response.getOutputStream();
    outputStream.writeTo(out);
    out.flush();
    out.close();
}
  • createProductExcel:处理创建产品规格书(Excel文件)的请求。
    • 使用@PostMapping注解指定这是POST请求处理方法。
    • @RequestBody ProductExcelReq productExcelReq获取请求体中的参数。
    • 验证所需图片文件是否存在,如果不存在则抛出异常。
    • 使用FileInputStream读取两个图片文件的内容。
    • 调用StoreUtil.createProductExcel方法生成Excel文件。
    • 将生成的Excel文件写入ByteArrayOutputStream
    • 设置HTTP响应头以确保浏览器下载文件而不是显示。
    • 获取HTTP响应输出流,并将Excel文件内容写入响应输出流中。

总结

BaseProductController类提供了成品管理的功能,包括:

  • 产品尺寸图和接线图导入:通过上传文件并调用服务层方法保存图片。
  • 创建产品规格书xlsx:根据请求参数生成包含产品信息的Excel文件,并提供给用户下载。

该控制器利用了Spring框架的强大功能,如依赖注入、请求映射和异常处理,同时也结合了Swagger注解以增强API文档的可读性和维护性。此外,通过Apache POI库实现了Excel文件的生成和处理,满足了业务需求中对于文件操作的要求。@RefreshScope注解的应用还使得配置属性可以在运行时刷新,增强了应用程序的灵活性和适应性。

package net.work.controller.base;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.work.request.base.BaseProductReq;
import net.work.request.base.ProductExcelReq;
import net.work.service.base.BaseProductService;
import net.work.util.JsonData;
import net.work.util.StoreUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@RefreshScope
@Api(tags = "成品管理")
@RestController
@RequestMapping("/api/base/v1/product/")
public class BaseProductController {

    @Value("${product.filePath}")
    private String filePath;

    @Autowired
    private BaseProductService baseProductService;

    @ApiOperation("产品尺寸图和接线图导入")
    @PostMapping("importProductImage")
    public JsonData importProductImage(@RequestParam("file") MultipartFile file, String productModel) throws Exception {
        return baseProductService.importProductImage(file, filePath, productModel);
    }

    @ApiOperation("创建产品规格书xlsxjavascript")
    @PostMapping("createProductExcel")
    public void createProductExcel(@RequestBody ProductExcelReq productExcelReq) throws Exception {
        String productModel = productExcelReq.getProductModel();
        File file1 = new File(filePath + productModel + "\\img1.png");
        if (!file1.exists()) {
            throw new Exception("当前产品型号【" + productModel + "】img1.png文件不存在!");
        }
        File file2 = new File(filePath + productModel + "\\img2.png");
        if (!file2.exists()) {
            throw new Exception("当前产品型号【" + productModel + "】img2.png文件不存在!");
        }

        InputStream inputStream1 = new FileInputStream(file1);
        InputStream inputStream2 = new FileInputStream(file2);

        Workbook workbook = StoreUtil.createProductExcel(filePath, inputStream1, inputStream2, productExcelReq);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();

        HttpServletResponse response = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getResponse();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + productExcelReq.getPpythonroductModel() + ".xlsx");

        OutputStream out = response.getOutputStream();
        outputStream.writeTo(out);
        out.flush();
        out.close();
    }

}

createProductExcel

定义了一个名为createProductExcel的静态方法,该方法用于创建一个基于模板的Excel文件(.xlsx),并根据提供的参数自定义内容。此方法使用了Apache POI库来操作Excel文件,并且能够根据不同的条件选择不同的模板文件和插入图片。

方法签名

public static Workbook createProductExcel(String filePath, InputStream inp2, InputStream inp3,
                                         ProductExcelReq productExcelReq)
  • 返回值Workbook对象,表示生成的Excel文件。
  • 参数
    • String filePath:模板文件所在的路径。
    • InputStream inp2InputStream inp3:两个输入流,分别包含要插入到Excel中的图片数据。
    • ProductExcelReq productExcelReq:请求对象,包含了生成Excel文件所需的各种信息。

模板选择逻辑

String templateName1 = "template1.xlsx";
String templateName2 = "template2.xlsx";
if (productExcelReq.getLanguage() == 1) {
    templateName1 = "template1_en.xlsx";
    templateName2 = "template2_en.xlsx";
}
  • 根据productExcelReq.getLanguage()的值选择不同的模板文件名。如果语言标识为1(可能代表英语),则使用带有“_en”后缀的模板文件名;否则,默认使用中文模板文件名。

流初始化与模板选择

try (InputStream inp0 = new FileInputStream(filePath + templateName1);
     InputStream inp1 = new FileInputStream(filePath + templateName2)) {
    InputStream inp = inp0;
    // 可以根据不同的类型决定使用哪个模板
    if (productExcelReq.getInstallType().contains("xxx")) {
        inp = inp1;
    }
    Workbook workbook = new XSSFWorkbook(inp);
  • 使用try-with-resources语句确保资源在使用完毕后自动关闭。
  • 打开两个模板文件的输入流inp0inp1
  • 根据productExcelReq.getInstallType()的内容判断是否需要切换到第二个模板文件inp1
  • 创建XSSFWorkbook实例,从选定的模板文件中加载工作簿。

图片插入

Sheet sheet = workbook.getSheetAt(0);
{
    byte[] bytes1 = IOUtils.toByteArray(inp2);
    byte[] bytes2 = IOUtils.toByteArray(inp3);
    int pictureIdx1 = workbook.addPicture(bytes1, Workbook.PICTURE_TYPE_PNG);
    int pictureIdx2 = workbook.addPicture(bytes2, Workbook.PICTURE_TYPE_PNG);

    CreationHelper helper = workbook.getCreationHelper();
    Drawing<?> drawing = sheet.createDrawingPatriarch();

    ClientAnchor anchor1 = helper.createClientAnchor();
    anchor1.setCol1(2);
    anchor1.setRow1(6);
    ClientAnchor anchor2 = helper.createClientAnchor();
    anchor2.setCol1(5);
    anchor2.setRow1(18);

    Picture pict1 = drawing.createPicture(anchor1, pictureIdx1);
    Picture pict2 = drawing.createPicture(anchor2, pictureIdx2);
    pict1.resize(4.08, 7.67);
    pict2.resize(1, 3.05);
  • 获取第一个工作表sheet
  • 将传入的图片输入流转换为字节数组,并添加到工作簿中作为图片资源。
  • 创建绘图工具Drawing和锚点ClientAnchor,用于确定图片的位置。
  • 在指定位置创建图片,并调整其大小。

修改单元格内容

// 修改单元格内容
Row row = sheet.getRow(15);
Cell cell = row.getCell(3);
cell.setCellValue(productExcelReq.getSpecification());

row = sheet.getRow(16);
cell = row.getCell(3);
cell.setCellValue(productExcelReq.getProductModel());

row = sheet.getRow(17);
cell = row.getCell(3);
cell.setCellValue(productExcelReq.getSwitchType());

row = sheet.getRow(18);
cell = row.getCell(3);
cell.setCellValue(productExcelReq.getWorkDistance());

row = sheet.getRow(19);
cell = row.getCell(3);
cell.setCellValue(productExcelReq.getInstallType());
  • 根据行号获取特定行,并修改第4列(索引为3)的单元格内容,设置为productExcelReq对象中对应的属性值。

异常处理

} catch (IOException e) {
    throw new RuntimeException(e);
}
  • 捕获可能发生的IOException异常,并将其包装成RuntimeException抛出,简化异常处理逻辑。

总结

createProductExcel方法的主要功能是基于模板创建一个自定义的Excel文件,并根据业务需求动态地插入图片和修改特定单元格的内容。通过这种方法,可以灵活地生成符合不同要求的产品规格书,支持多语言版本和多种安装类型的文档生成。此外,使用Apache POI库使得Excel文件的操作变得简单直接,同时利用Java的IO流机制确保了资源的有效管理和安全释放。

    public static Workbook createProductExcel(String filePath, InputStream inp2, InputStream inp3,
                                              ProductExcelReq productExcelReq) {
        String templateName1 = "template1.xlsx";
        String templateName2 = "template2.xlsx";
        if (productExcelReq.getLanguage() == 1) {
            templateName1 = "template1_en.xlsx";
            templateName2 = "template2_en.xlsx";
        }
        try (InputStream inp0 = new FileInputStream(filePath + templateName1);
             InputStream inp1 = new FileInputStream(filePath + templateName2)) {
            InputStream inp = inp0;
            // 可以根据不同的类型决定使用哪个模板
            if (productExcelReq.getInstallType().contains("xxx")) {
                inp = inp1;
            }
            Workbook workbook = new XSSFWorkbook(inp);
            Sheet sheet = workbook.getSheetAt(0);
            {
                byte[] bytes1 = IOUtils.toByteArray(inp2);
                byte[] bytes2 = IOUtils.toByteArray(inp3);
                int pictureIdx1 = workbook.addPicture(bytes1, Workbook.PICTURE_TYPE_PNG);
                int pictureIdx2 = workbook.addPicture(bytes2, Workbook.PICTURE_TYPE_PNG);

                CreationHelper helper = workbook.getCreationHelper();
                Drawing<?> drawing = sheet.createDrawingPatriarch();

                ClientAnchor anchor1 = helper.createClientAnchor();
                anchor1.setCol1(2);
                anchor1.setRow1(6);
                ClientAnchor anchor2 = helper.createClientAnchor();
                anchor2.setCol1(5);
                anchor2.setRow1(18);

                Picture pict1 = drawing.createPicture(anchor1, pictureIdx1);
                Picture pict2 = drawing.createPicture(anchor2, pictureIdx2);
                pict1.resize(4.08, 7.67);
                pict2.resize(1, 3.05);

                // 修改单元格内容
                Row row = sheet.getRow(15);
                Cell cell = row.getCell(3);
                cell.setCellValue(productExcelReq.getSpecification());

                row = sheet.getRow(16);
                cell = row.getCell(3);
                cell.setCellValue(productExcelReq.getProductModel());

                row = sheet.getRow(17);
                cell = row.getCell(3);
                cell.setCellValue(productExcelReq.getSwitchType());

                row = sheet.getRow(18);
                cell = row.getCell(3);
                cell.setCellValue(productExcelReq.getWorkDistance());

                row = sheet.getRow(19);
                cell = row.getCell(3);
                cell.setCellValue(productExcelReq.getInstallType());

                return workbook;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

总结 

到此这篇关于Java操作xls替换文本或图片的功能实现的文章就介绍到这了,更多相关Java操作xls替换文本或图片内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于Java操作xls替换文本或图片的功能实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1152850

相关文章

Java Stream流与使用操作指南

《JavaStream流与使用操作指南》Stream不是数据结构,而是一种高级的数据处理工具,允许你以声明式的方式处理数据集合,类似于SQL语句操作数据库,本文给大家介绍JavaStream流与使用... 目录一、什么是stream流二、创建stream流1.单列集合创建stream流2.双列集合创建str

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv