Java操作xls替換文本或圖片的功能實(shí)現(xiàn)
準(zhǔn)備xls模板文件:template.xls

要求根據(jù)不同的產(chǎn)品型號和圖片,插入到模板文件中,然后再填充產(chǎn)品信息。
準(zhǔn)備需要替換的圖片和數(shù)據(jù)

功能實(shí)現(xiàn)
定義了一個名為BaseProductController的RESTful控制器,它負(fù)責(zé)處理與成品管理相關(guān)的HTTP請求。該控制器使用了Spring框架、Swagger注解以及Apache POI庫來處理文件上傳和Excel文檔生成。
包聲明與導(dǎo)入
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;
- 包聲明:指定了類所在的包路徑。
- 導(dǎo)入:引入了必要的類和接口,包括Swagger注解、自定義請求對象和服務(wù)接口、工具類、Apache POI庫、Spring框架注解等。
類聲明與注解
@RefreshScope
@Api(tags = "成品管理")
@RestController
@RequestMapping("/api/base/v1/product/")
public class BaseProductController {@RefreshScope:允許在運(yùn)行時刷新配置屬性,適用于Spring Cloud環(huán)境中的動態(tài)配置更新。@Api(tags = "成品管理"):Swagger注解,用于標(biāo)記此控制器屬于“成品管理”模塊,以便在API文檔中分類。@RestController:Spring MVC注解,表明這是一個RESTful風(fēng)格的控制器,返回的數(shù)據(jù)將直接寫入HTTP響應(yīng)體中。@RequestMapping("/api/base/v1/product/"):指定該控制器下的所有端點(diǎn)的基礎(chǔ)URL路徑為/api/base/v1/product/。
注入依賴與配置屬性
@Value("${product.filePath}")
private String filePath;
@Autowired
private BaseProductService baseProductService;@Value("${product.filePath}"):從外部化配置文件中讀取產(chǎn)品文件路徑,并注入到filePath字段。@Autowired:自動注入BaseProductService服務(wù)實(shí)例,用于處理業(yè)務(wù)邏輯。
方法解析
產(chǎn)品尺寸圖和接線圖導(dǎo)入
@ApiOperation("產(chǎn)品尺寸圖和接線圖導(dǎo)入")
@PostMapping("importProductImage")
public JsonData importProductImage(@RequestParam("file") MultipartFile file, String productModel) throws Exception {
return baseProductService.importProductImage(file, filePath, productModel);
}importProductImage:處理產(chǎn)品尺寸圖和接線圖的上傳。- 使用
@PostMapping注解指定這是POST請求處理方法。 @RequestParam("file")獲取上傳的文件,String productModel獲取產(chǎn)品型號。- 調(diào)用
baseProductService.importProductImage方法進(jìn)行實(shí)際的文件處理,并返回處理結(jié)果作為JSON數(shù)據(jù)。
- 使用
創(chuàng)建產(chǎn)品規(guī)格書xlsx
@ApiOperation("創(chuàng)建產(chǎn)品規(guī)格書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("當(dāng)前產(chǎn)品型號【" + productModel + "】img1.png文件不存在!");
}
File file2 = new File(filePath + productModel + "\\img2.png");
if (!file2.exists()) {
throw new Exception("當(dāng)前產(chǎn)品型號【" + 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:處理創(chuàng)建產(chǎn)品規(guī)格書(Excel文件)的請求。- 使用
@PostMapping注解指定這是POST請求處理方法。 @RequestBody ProductExcelReq productExcelReq獲取請求體中的參數(shù)。- 驗(yàn)證所需圖片文件是否存在,如果不存在則拋出異常。
- 使用
FileInputStream讀取兩個圖片文件的內(nèi)容。 - 調(diào)用
StoreUtil.createProductExcel方法生成Excel文件。 - 將生成的Excel文件寫入
ByteArrayOutputStream。 - 設(shè)置HTTP響應(yīng)頭以確保瀏覽器下載文件而不是顯示。
- 獲取HTTP響應(yīng)輸出流,并將Excel文件內(nèi)容寫入響應(yīng)輸出流中。
- 使用
總結(jié)
BaseProductController類提供了成品管理的功能,包括:
- 產(chǎn)品尺寸圖和接線圖導(dǎo)入:通過上傳文件并調(diào)用服務(wù)層方法保存圖片。
- 創(chuàng)建產(chǎn)品規(guī)格書xlsx:根據(jù)請求參數(shù)生成包含產(chǎn)品信息的Excel文件,并提供給用戶下載。
該控制器利用了Spring框架的強(qiáng)大功能,如依賴注入、請求映射和異常處理,同時也結(jié)合了Swagger注解以增強(qiáng)API文檔的可讀性和維護(hù)性。此外,通過Apache POI庫實(shí)現(xiàn)了Excel文件的生成和處理,滿足了業(yè)務(wù)需求中對于文件操作的要求。@RefreshScope注解的應(yīng)用還使得配置屬性可以在運(yùn)行時刷新,增強(qiáng)了應(yīng)用程序的靈活性和適應(yīng)性。
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("產(chǎn)品尺寸圖和接線圖導(dǎo)入")
@PostMapping("importProductImage")
public JsonData importProductImage(@RequestParam("file") MultipartFile file, String productModel) throws Exception {
return baseProductService.importProductImage(file, filePath, productModel);
}
@ApiOperation("創(chuàng)建產(chǎn)品規(guī)格書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("當(dāng)前產(chǎn)品型號【" + productModel + "】img1.png文件不存在!");
}
File file2 = new File(filePath + productModel + "\\img2.png");
if (!file2.exists()) {
throw new Exception("當(dāng)前產(chǎn)品型號【" + 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的靜態(tài)方法,該方法用于創(chuàng)建一個基于模板的Excel文件(.xlsx),并根據(jù)提供的參數(shù)自定義內(nèi)容。此方法使用了Apache POI庫來操作Excel文件,并且能夠根據(jù)不同的條件選擇不同的模板文件和插入圖片。
方法簽名
public static Workbook createProductExcel(String filePath, InputStream inp2, InputStream inp3,
ProductExcelReq productExcelReq)- 返回值:
Workbook對象,表示生成的Excel文件。 - 參數(shù):
String filePath:模板文件所在的路徑。InputStream inp2,InputStream inp3:兩個輸入流,分別包含要插入到Excel中的圖片數(shù)據(jù)。ProductExcelReq productExcelReq:請求對象,包含了生成Excel文件所需的各種信息。
模板選擇邏輯
String templateName1 = "template1.xlsx";
String templateName2 = "template2.xlsx";
if (productExcelReq.getLanguage() == 1) {
templateName1 = "template1_en.xlsx";
templateName2 = "template2_en.xlsx";
}- 根據(jù)
productExcelReq.getLanguage()的值選擇不同的模板文件名。如果語言標(biāo)識為1(可能代表英語),則使用帶有“_en”后綴的模板文件名;否則,默認(rèn)使用中文模板文件名。
流初始化與模板選擇
try (InputStream inp0 = new FileInputStream(filePath + templateName1);
InputStream inp1 = new FileInputStream(filePath + templateName2)) {
InputStream inp = inp0;
// 可以根據(jù)不同的類型決定使用哪個模板
if (productExcelReq.getInstallType().contains("xxx")) {
inp = inp1;
}
Workbook workbook = new XSSFWorkbook(inp);- 使用
try-with-resources語句確保資源在使用完畢后自動關(guān)閉。 - 打開兩個模板文件的輸入流
inp0和inp1。 - 根據(jù)
productExcelReq.getInstallType()的內(nèi)容判斷是否需要切換到第二個模板文件inp1。 - 創(chuàng)建
XSSFWorkbook實(shí)例,從選定的模板文件中加載工作簿。
圖片插入
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。 - 將傳入的圖片輸入流轉(zhuǎn)換為字節(jié)數(shù)組,并添加到工作簿中作為圖片資源。
- 創(chuàng)建繪圖工具
Drawing和錨點(diǎn)ClientAnchor,用于確定圖片的位置。 - 在指定位置創(chuàng)建圖片,并調(diào)整其大小。
修改單元格內(nèi)容
// 修改單元格內(nèi)容 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());
- 根據(jù)行號獲取特定行,并修改第4列(索引為3)的單元格內(nèi)容,設(shè)置為
productExcelReq對象中對應(yīng)的屬性值。
異常處理
} catch (IOException e) {
throw new RuntimeException(e);
}- 捕獲可能發(fā)生的
IOException異常,并將其包裝成RuntimeException拋出,簡化異常處理邏輯。
總結(jié)
createProductExcel方法的主要功能是基于模板創(chuàng)建一個自定義的Excel文件,并根據(jù)業(yè)務(wù)需求動態(tài)地插入圖片和修改特定單元格的內(nèi)容。通過這種方法,可以靈活地生成符合不同要求的產(chǎn)品規(guī)格書,支持多語言版本和多種安裝類型的文檔生成。此外,使用Apache POI庫使得Excel文件的操作變得簡單直接,同時利用Java的IO流機(jī)制確保了資源的有效管理和安全釋放。
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;
// 可以根據(jù)不同的類型決定使用哪個模板
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);
// 修改單元格內(nèi)容
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);
}
}總結(jié)
到此這篇關(guān)于Java操作xls替換文本或圖片的功能實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Java操作xls替換文本或圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于SpringBoot2.0默認(rèn)使用Redis連接池的配置操作
這篇文章主要介紹了基于SpringBoot2.0默認(rèn)使用Redis連接池的配置操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12
Java自動化實(shí)現(xiàn)查找并替換PDF中的文本
這篇文章主要為大家詳細(xì)介紹了如何使用強(qiáng)大的 Java PDF 處理庫 Spire.PDF for Java,輕松實(shí)現(xiàn) PDF 文檔中的文本查找與替換功能,需要的小伙伴可以了解下2025-08-08
Java案例之HashMap集合存儲學(xué)生對象并遍歷
這篇文章主要介紹了Java案例之HashMap集合存儲學(xué)生對象并遍歷,創(chuàng)建一個HashMap集合,鍵是學(xué)號(String),值是學(xué)生對象(Student),存儲三個鍵值對元素并遍歷,下文具體操作需要的朋友可以參考一下2022-04-04
解決java Graphics drawImage 無法顯示圖片的問題
這篇文章主要介紹了解決java Graphics drawImage 無法顯示圖片的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
Java解析Excel文件并把數(shù)據(jù)存入數(shù)據(jù)庫
本篇文章主要介紹了Java解析Excel文件并把數(shù)據(jù)存入數(shù)據(jù)庫 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
Java使用Mockito進(jìn)行模擬和測試樁實(shí)踐過程
本文介紹了Mockito框架的基本概念、使用方法和進(jìn)階用法,包括模擬對象、測試樁、參數(shù)匹配、異步測試、void方法的樁方法和驗(yàn)證、mock靜態(tài)方法和final方法等內(nèi)容,Mockito是一個流行的Java模擬框架,具有簡單易用、支持廣泛、文檔豐富的優(yōu)點(diǎn)2026-04-04
Spring Boot集成Swagger接口分類與各元素排序問題
這篇文章主要介紹了Spring Boot集成Swagger接口分類與各元素排序問題,首先我們需要對Swagger中的接口也就是以Controller 層作為第一級梯度進(jìn)行組織的,Controller在我們實(shí)際開發(fā)中,與其他具體接口之間是存在一對多的關(guān)系,本文給大家介紹的非常詳細(xì),需要的朋友參考下吧2023-10-10
Springboot微服務(wù)項(xiàng)目整合Kafka實(shí)現(xiàn)文章上下架功能
這篇文章主要介紹了Springboot微服務(wù)項(xiàng)目整合Kafka實(shí)現(xiàn)文章上下架功能,包括Kafka消息發(fā)送快速入門及相關(guān)功能引入,本文通過示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07

