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

 更新时间:2024年12月30日 10:08:42   作者:道友老李  
这篇文章主要给大家介绍了关于Java操作xls替换文本或图片功能实现的相关资料,文中通过示例代码讲解了文件上传、文件处理和Excel文件生成,需要的朋友可以参考下

准备xls模板文件:template.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.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;
  • 包声明:指定了类所在的包路径。
  • 导入:引入了必要的类和接口,包括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", "attachment;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("创建产品规格书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", "attachment;filename=" + productExcelReq.getProductModel() + ".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替换文本或图片内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java实现File转换MultipartFile格式的例子

    Java实现File转换MultipartFile格式的例子

    本文主要介绍了Java实现File转换MultipartFile格式的例子,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • JavaSE中比较器、深拷贝浅拷贝举例详解

    JavaSE中比较器、深拷贝浅拷贝举例详解

    在Java中一切都可以视为对象,在Java中我们经常使用引用去操作对象,下面这篇文章主要给大家介绍了关于JavaSE中比较器、深拷贝浅拷贝的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-07-07
  • Java后台线程操作示例【守护线程】

    Java后台线程操作示例【守护线程】

    这篇文章主要介绍了Java后台线程操作,结合实例形式分析了java守护线程相关原理、操作技巧与使用注意事项,需要的朋友可以参考下
    2019-09-09
  • lombok注解介绍小结

    lombok注解介绍小结

    lombok是一个可以帮助我们简化java代码编写的工具类,这篇文章主要介绍了lombok注解介绍小结,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • Spring boot2X Consul如何通过RestTemplate实现服务调用

    Spring boot2X Consul如何通过RestTemplate实现服务调用

    这篇文章主要介绍了spring boot2X Consul如何通过RestTemplate实现服务调用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • 基于编译虚拟机jvm—openjdk的编译详解

    基于编译虚拟机jvm—openjdk的编译详解

    下面小编就为大家分享一篇基于编译虚拟机jvm—openjdk的编译详解,具有很好的参考价值,希望对大家有所帮助
    2017-12-12
  • Java实现上传和下载功能(支持多个文件同时上传)

    Java实现上传和下载功能(支持多个文件同时上传)

    这篇文章主要介绍了Java实现上传和下载功能,支持多个文件同时上传,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-12-12
  • java中为何重写equals时必须重写hashCode方法详解

    java中为何重写equals时必须重写hashCode方法详解

    这篇文章主要给大家介绍了关于java中为什么重写equals时必须重写hashCode方法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-11-11
  • Java中的异步回调问题

    Java中的异步回调问题

    这篇文章主要介绍了Java中的异步回调问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • nacos配置中心持久化相关配置方式

    nacos配置中心持久化相关配置方式

    这篇文章主要介绍了nacos配置中心持久化相关配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11

最新评论