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

相关文章

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

sysmain服务可以禁用吗? 电脑sysmain服务关闭后的影响与操作指南

《sysmain服务可以禁用吗?电脑sysmain服务关闭后的影响与操作指南》在Windows系统中,SysMain服务(原名Superfetch)作为一个旨在提升系统性能的关键组件,一直备受用户关... 在使用 Windows 系统时,有时候真有点像在「开盲盒」。全新安装系统后的「默认设置」,往往并不尽编

Redis实现高效内存管理的示例代码

《Redis实现高效内存管理的示例代码》Redis内存管理是其核心功能之一,为了高效地利用内存,Redis采用了多种技术和策略,如优化的数据结构、内存分配策略、内存回收、数据压缩等,下面就来详细的介绍... 目录1. 内存分配策略jemalloc 的使用2. 数据压缩和编码ziplist示例代码3. 优化的

Java Stream 并行流简介、使用与注意事项小结

《JavaStream并行流简介、使用与注意事项小结》Java8并行流基于StreamAPI,利用多核CPU提升计算密集型任务效率,但需注意线程安全、顺序不确定及线程池管理,可通过自定义线程池与C... 目录1. 并行流简介​特点:​2. 并行流的简单使用​示例:并行流的基本使用​3. 配合自定义线程池​示

从原理到实战解析Java Stream 的并行流性能优化

《从原理到实战解析JavaStream的并行流性能优化》本文给大家介绍JavaStream的并行流性能优化:从原理到实战的全攻略,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的... 目录一、并行流的核心原理与适用场景二、性能优化的核心策略1. 合理设置并行度:打破默认阈值2. 避免装箱

解决升级JDK报错:module java.base does not“opens java.lang.reflect“to unnamed module问题

《解决升级JDK报错:modulejava.basedoesnot“opensjava.lang.reflect“tounnamedmodule问题》SpringBoot启动错误源于Jav... 目录问题描述原因分析解决方案总结问题描述启动sprintboot时报以下错误原因分析编程异js常是由Ja

基于C#实现PDF转图片的详细教程

《基于C#实现PDF转图片的详细教程》在数字化办公场景中,PDF文件的可视化处理需求日益增长,本文将围绕Spire.PDFfor.NET这一工具,详解如何通过C#将PDF转换为JPG、PNG等主流图片... 目录引言一、组件部署二、快速入门:PDF 转图片的核心 C# 代码三、分辨率设置 - 清晰度的决定因