java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java操作xls替换文本或图片

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

作者:道友老李

这篇文章主要给大家介绍了关于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;

类声明与注解

@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);
}

创建产品规格书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();
}

总结

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

该控制器利用了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)

模板选择逻辑

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());

异常处理

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

总结

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替换文本或图片内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文