Java操作xls替換文本或圖片的功能實(shí)現(xiàn)
準(zhǔn)備xls模板文件:template.xls
要求根據(jù)不同的產(chǎn)品型號(hào)和圖片,插入到模板文件中,然后再填充產(chǎn)品信息。
準(zhǔn)備需要替換的圖片和數(shù)據(jù)
功能實(shí)現(xiàn)
定義了一個(gè)名為BaseProductController
的RESTful控制器,它負(fù)責(zé)處理與成品管理相關(guān)的HTTP請(qǐng)求。該控制器使用了Spring框架、Swagger注解以及Apache POI庫(kù)來(lái)處理文件上傳和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;
- 包聲明:指定了類(lèi)所在的包路徑。
- 導(dǎo)入:引入了必要的類(lèi)和接口,包括Swagger注解、自定義請(qǐng)求對(duì)象和服務(wù)接口、工具類(lèi)、Apache POI庫(kù)、Spring框架注解等。
類(lèi)聲明與注解
@RefreshScope @Api(tags = "成品管理") @RestController @RequestMapping("/api/base/v1/product/") public class BaseProductController {
@RefreshScope
:允許在運(yùn)行時(shí)刷新配置屬性,適用于Spring Cloud環(huán)境中的動(dòng)態(tài)配置更新。@Api(tags = "成品管理")
:Swagger注解,用于標(biāo)記此控制器屬于“成品管理”模塊,以便在API文檔中分類(lèi)。@RestController
:Spring MVC注解,表明這是一個(gè)RESTful風(fēng)格的控制器,返回的數(shù)據(jù)將直接寫(xiě)入HTTP響應(yīng)體中。@RequestMapping("/api/base/v1/product/")
:指定該控制器下的所有端點(diǎn)的基礎(chǔ)URL路徑為/api/base/v1/product/
。
注入依賴(lài)與配置屬性
@Value("${product.filePath}") private String filePath; @Autowired private BaseProductService baseProductService;
@Value("${product.filePath}")
:從外部化配置文件中讀取產(chǎn)品文件路徑,并注入到filePath
字段。@Autowired
:自動(dòng)注入BaseProductService
服務(wù)實(shí)例,用于處理業(yè)務(wù)邏輯。
方法解析
產(chǎn)品尺寸圖和接線(xiàn)圖導(dǎo)入
@ApiOperation("產(chǎn)品尺寸圖和接線(xià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)品尺寸圖和接線(xiàn)圖的上傳。- 使用
@PostMapping
注解指定這是POST請(qǐng)求處理方法。 @RequestParam("file")
獲取上傳的文件,String productModel
獲取產(chǎn)品型號(hào)。- 調(diào)用
baseProductService.importProductImage
方法進(jìn)行實(shí)際的文件處理,并返回處理結(jié)果作為JSON數(shù)據(jù)。
- 使用
創(chuàng)建產(chǎn)品規(guī)格書(shū)xlsx
@ApiOperation("創(chuàng)建產(chǎn)品規(guī)格書(shū)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)品型號(hào)【" + productModel + "】img1.png文件不存在!"); } File file2 = new File(filePath + productModel + "\\img2.png"); if (!file2.exists()) { throw new Exception("當(dāng)前產(chǎn)品型號(hào)【" + 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ī)格書(shū)(Excel文件)的請(qǐng)求。- 使用
@PostMapping
注解指定這是POST請(qǐng)求處理方法。 @RequestBody ProductExcelReq productExcelReq
獲取請(qǐng)求體中的參數(shù)。- 驗(yàn)證所需圖片文件是否存在,如果不存在則拋出異常。
- 使用
FileInputStream
讀取兩個(gè)圖片文件的內(nèi)容。 - 調(diào)用
StoreUtil.createProductExcel
方法生成Excel文件。 - 將生成的Excel文件寫(xiě)入
ByteArrayOutputStream
。 - 設(shè)置HTTP響應(yīng)頭以確保瀏覽器下載文件而不是顯示。
- 獲取HTTP響應(yīng)輸出流,并將Excel文件內(nèi)容寫(xiě)入響應(yīng)輸出流中。
- 使用
總結(jié)
BaseProductController
類(lèi)提供了成品管理的功能,包括:
- 產(chǎn)品尺寸圖和接線(xiàn)圖導(dǎo)入:通過(guò)上傳文件并調(diào)用服務(wù)層方法保存圖片。
- 創(chuàng)建產(chǎn)品規(guī)格書(shū)xlsx:根據(jù)請(qǐng)求參數(shù)生成包含產(chǎn)品信息的Excel文件,并提供給用戶(hù)下載。
該控制器利用了Spring框架的強(qiáng)大功能,如依賴(lài)注入、請(qǐng)求映射和異常處理,同時(shí)也結(jié)合了Swagger注解以增強(qiáng)API文檔的可讀性和維護(hù)性。此外,通過(guò)Apache POI庫(kù)實(shí)現(xiàn)了Excel文件的生成和處理,滿(mǎn)足了業(yè)務(wù)需求中對(duì)于文件操作的要求。@RefreshScope
注解的應(yīng)用還使得配置屬性可以在運(yùn)行時(shí)刷新,增強(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)品尺寸圖和接線(xià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ī)格書(shū)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)品型號(hào)【" + productModel + "】img1.png文件不存在!"); } File file2 = new File(filePath + productModel + "\\img2.png"); if (!file2.exists()) { throw new Exception("當(dāng)前產(chǎn)品型號(hào)【" + 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
定義了一個(gè)名為createProductExcel
的靜態(tài)方法,該方法用于創(chuàng)建一個(gè)基于模板的Excel文件(.xlsx),并根據(jù)提供的參數(shù)自定義內(nèi)容。此方法使用了Apache POI庫(kù)來(lái)操作Excel文件,并且能夠根據(jù)不同的條件選擇不同的模板文件和插入圖片。
方法簽名
public static Workbook createProductExcel(String filePath, InputStream inp2, InputStream inp3, ProductExcelReq productExcelReq)
- 返回值:
Workbook
對(duì)象,表示生成的Excel文件。 - 參數(shù):
String filePath
:模板文件所在的路徑。InputStream inp2
,InputStream inp3
:兩個(gè)輸入流,分別包含要插入到Excel中的圖片數(shù)據(jù)。ProductExcelReq productExcelReq
:請(qǐng)求對(duì)象,包含了生成Excel文件所需的各種信息。
模板選擇邏輯
String templateName1 = "template1.xlsx"; String templateName2 = "template2.xlsx"; if (productExcelReq.getLanguage() == 1) { templateName1 = "template1_en.xlsx"; templateName2 = "template2_en.xlsx"; }
- 根據(jù)
productExcelReq.getLanguage()
的值選擇不同的模板文件名。如果語(yǔ)言標(biāo)識(shí)為1(可能代表英語(yǔ)),則使用帶有“_en”后綴的模板文件名;否則,默認(rèn)使用中文模板文件名。
流初始化與模板選擇
try (InputStream inp0 = new FileInputStream(filePath + templateName1); InputStream inp1 = new FileInputStream(filePath + templateName2)) { InputStream inp = inp0; // 可以根據(jù)不同的類(lèi)型決定使用哪個(gè)模板 if (productExcelReq.getInstallType().contains("xxx")) { inp = inp1; } Workbook workbook = new XSSFWorkbook(inp);
- 使用
try-with-resources
語(yǔ)句確保資源在使用完畢后自動(dòng)關(guān)閉。 - 打開(kāi)兩個(gè)模板文件的輸入流
inp0
和inp1
。 - 根據(jù)
productExcelReq.getInstallType()
的內(nèi)容判斷是否需要切換到第二個(gè)模板文件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);
- 獲取第一個(gè)工作表
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ù)行號(hào)獲取特定行,并修改第4列(索引為3)的單元格內(nèi)容,設(shè)置為
productExcelReq
對(duì)象中對(duì)應(yīng)的屬性值。
異常處理
} catch (IOException e) { throw new RuntimeException(e); }
- 捕獲可能發(fā)生的
IOException
異常,并將其包裝成RuntimeException
拋出,簡(jiǎn)化異常處理邏輯。
總結(jié)
createProductExcel
方法的主要功能是基于模板創(chuàng)建一個(gè)自定義的Excel文件,并根據(jù)業(yè)務(wù)需求動(dòng)態(tài)地插入圖片和修改特定單元格的內(nèi)容。通過(guò)這種方法,可以靈活地生成符合不同要求的產(chǎn)品規(guī)格書(shū),支持多語(yǔ)言版本和多種安裝類(lèi)型的文檔生成。此外,使用Apache POI庫(kù)使得Excel文件的操作變得簡(jiǎn)單直接,同時(shí)利用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ù)不同的類(lèi)型決定使用哪個(gè)模板 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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)File轉(zhuǎn)換MultipartFile格式的例子
本文主要介紹了Java實(shí)現(xiàn)File轉(zhuǎn)換MultipartFile格式的例子,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07Java后臺(tái)線(xiàn)程操作示例【守護(hù)線(xiàn)程】
這篇文章主要介紹了Java后臺(tái)線(xiàn)程操作,結(jié)合實(shí)例形式分析了java守護(hù)線(xiàn)程相關(guān)原理、操作技巧與使用注意事項(xiàng),需要的朋友可以參考下2019-09-09Spring boot2X Consul如何通過(guò)RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用
這篇文章主要介紹了spring boot2X Consul如何通過(guò)RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12Java實(shí)現(xiàn)上傳和下載功能(支持多個(gè)文件同時(shí)上傳)
這篇文章主要介紹了Java實(shí)現(xiàn)上傳和下載功能,支持多個(gè)文件同時(shí)上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12java中為何重寫(xiě)equals時(shí)必須重寫(xiě)hashCode方法詳解
這篇文章主要給大家介紹了關(guān)于java中為什么重寫(xiě)equals時(shí)必須重寫(xiě)hashCode方法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11