方式一 spire.xls.free(沒找設置分辨率的方法)
macOs開發Java GUI程序提示缺少字體問題解決?
?Spire.XLS:一款Excel處理神器_spire.xls免費版和收費版的區別-CSDN博客
官方文檔?
Spire.XLS for Java 中文教程
<dependency><groupId>e-iceblue</groupId><artifactId>spire.xls.free</artifactId><version>5.1.0</version></dependency><repositories><repository><id>e-iceblue</id><name>e-iceblue</name><url>https://repo.e-iceblue.cn/repository/maven-public/</url></repository></repositories>
/*** 功能描述: 處理將Excel文件轉換為圖片并提供下載的請求。* 參數說明:* excelFilePath: 存儲在服務器上的Excel文件的絕對路徑。* 返回值說明: ResponseEntity 包含圖片文件流,供瀏覽器下載。* 使用示例:* GET /downloadExcelAsImage?excelFilePath=/path/to/your/excel.xlsx*/@GetMapping( "/downloadImage/{id}")public ResponseEntity<InputStreamResource> downloadExcelAsImage(@PathVariable("id") String id) throws IOException {// 調用服務層方法將Excel轉換為圖片File imageFile = resultHistoryService.convertFromFilePath(id);// 設置HTTP頭,用于文件下載HttpHeaders headers = new HttpHeaders();headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + imageFile.getName());headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");headers.add(HttpHeaders.PRAGMA, "no-cache");headers.add(HttpHeaders.EXPIRES, "0");InputStreamResource resource = new InputStreamResource(new FileInputStream(imageFile));return ResponseEntity.ok().headers(headers).contentLength(imageFile.length())// 或者根據實際生成的圖片類型調整 MediaType.IMAGE_JPEG 等.contentType(MediaType.IMAGE_PNG).body(resource);}
public File convertFromFilePath(String id) throws IOException {ResultHistoryDO resultHistoryDO = resultHistoryDao.get(id);String uploadPath = bootdoConfig.getUploadPath();String fileurl = resultHistoryDO.getFileurl();String[] split = fileurl.split("/files/");String fileName =uploadPath+ split[1] ;Workbook workbook = new Workbook();// 加載Excel文檔workbook.loadFromFile(fileName);// 獲取第一個工作表 (您可以根據需要選擇特定的工作表)Worksheet sheet = workbook.getWorksheets().get(0);// 定義輸出圖片的文件名和路徑 (這里我們將其保存在臨時目錄)// 您可以根據需要更改保存路徑和文件名邏輯File outputFile = File.createTempFile("excel_image_", ".png");// 將工作表保存為圖片sheet.saveToImage(outputFile.getAbsolutePath());return outputFile;}
方式二aspose-cells(推薦設置分辨率轉出的圖片更清晰)
?
<dependency><groupId>com.luhuiguo</groupId><artifactId>aspose-cells</artifactId><version>23.1</version></dependency>
?
package com.charsming.common.domain;/*** 功能描述: 用于封裝圖片數據及其元數據的包裝類。*/
public class ImageDataWrapper {// 圖片的字節數組private byte[] data;// 建議的下載文件名private String fileName;// 圖片的MIME類型 (例如 "image/png")private String contentType;/*** 功能描述: ImageDataWrapper的構造函數。* 參數: data - 圖片的字節數組。* 參數: fileName - 建議的下載文件名。* 參數: contentType - 圖片的MIME類型。*/public ImageDataWrapper(byte[] data, String fileName, String contentType) {this.data = data;this.fileName = fileName;this.contentType = contentType;}// Getter 方法public byte[] getData() {return data;}public String getFileName() {return fileName;}public String getContentType() {return contentType;}
}
@GetMapping("/downloadImage/{id}")public ResponseEntity<InputStreamResource> downloadExcelAsImage(@PathVariable("id") String id, HttpServletResponse response) throws Exception {try {// logger.info("請求下載圖片,ID: {}", id); // 日志記錄ImageDataWrapper imageData = resultHistoryService.convertExcelToImageData(id);HttpHeaders headers = new HttpHeaders();// 設置Content-Disposition,提示瀏覽器下載并指定文件名headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + imageData.getFileName() + "\"");// 其他緩存控制相關的頭信息 (可選,但推薦)headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");headers.add(HttpHeaders.PRAGMA, "no-cache");headers.add(HttpHeaders.EXPIRES, "0");InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(imageData.getData()));// logger.info("成功生成圖片: {}, 大小: {} bytes", imageData.getFileName(), imageData.getData().length); // 日志記錄return ResponseEntity.ok().headers(headers).contentLength(imageData.getData().length).contentType(MediaType.parseMediaType(imageData.getContentType())).body(resource);} catch (Exception e) {// logger.error("下載圖片失敗,ID: {}. 錯誤: {}", id, e.getMessage(), e); // 記錄異常堆棧// 在發生錯誤時,返回一個帶有錯誤信息的ResponseEntity// 您可以根據需要定制錯誤響應的格式,例如返回一個JSON對象String errorMessage = "下載圖片失敗: " + e.getMessage();InputStreamResource errorResource = new InputStreamResource(new ByteArrayInputStream(errorMessage.getBytes(java.nio.charset.StandardCharsets.UTF_8)));return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.TEXT_PLAIN).body(errorResource);}
@Overridepublic ImageDataWrapper convertExcelToImageData(String id) throws Exception {ResultHistoryDO resultHistoryDO = resultHistoryDao.get(id);if (resultHistoryDO == null || resultHistoryDO.getFileurl() == null) {throw new Exception("未找到ID為 " + id + " 的結果歷史記錄或文件路徑為空。");}String uploadPath = bootdoConfig.getUploadPath();String fileurl = resultHistoryDO.getFileurl();// 注意:此處的分割邏輯可能需要根據您的實際fileurl格式調整String[] split = fileurl.split("/files/");if (split.length < 2) {throw new Exception("文件路徑格式不正確,無法提取文件名: " + fileurl);}String excelFilePath = uploadPath + split[1];Workbook workbook = null;// 使用try-with-resources確保baos關閉try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {workbook = new Workbook(excelFilePath);Worksheet worksheet = workbook.getWorksheets().get(0);// --- 全局修改默認字體 開始 ---Style defaultStyle = workbook.getDefaultStyle();Font defaultFont = defaultStyle.getFont();defaultFont.setName("Times New Roman"); // 設置全局默認字體名稱defaultFont.setSize(11); // 設置全局默認字體大小// defaultFont.setBold(false); // 根據需要設置其他屬性workbook.setDefaultStyle(defaultStyle); // 應用修改后的默認樣式到整個工作簿ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();imgOptions.setImageType(ImageType.PNG);imgOptions.setHorizontalResolution(800);imgOptions.setVerticalResolution(800);SheetRender sr = new SheetRender(worksheet, imgOptions);if (sr.getPageCount() > 0) {// 渲染第一頁int pageIndexToRender = 0;sr.toImage(pageIndexToRender, baos);// baos.flush(); // ByteArrayOutputStream的flush是空操作,可以省略byte[] imageBytes = baos.toByteArray();String originalFileName = new File(excelFilePath).getName();String baseName = originalFileName.contains(".") ? originalFileName.substring(0, originalFileName.lastIndexOf('.')) : originalFileName;String suggestedFileName = baseName + (pageIndexToRender + 1) + ".png";String contentType = "image/png";return new ImageDataWrapper(imageBytes, suggestedFileName, contentType);} else {throw new Exception("Excel工作表 " + excelFilePath + " 為空或無法渲染成圖片。");}} finally {if (workbook != null) {// 根據Aspose.Cells文檔,Workbook類實現了IDisposable接口,// 在.NET中通常用using語句處理。在Java中,如果它有close()或dispose()方法,應在此調用。// 查閱文檔,Aspose.Cells for Java 通常不需要顯式調用 workbook.dispose(),垃圾回收器會處理。// 但如果遇到內存問題,可以檢查是否有相關API。}}}
async function downloadImage(imageId) {// 構建下載文件的 URLconst downloadUrl = `${prefix}/downloadImage/${imageId}`;let loadingIndex; // 用于存儲 Layui 加載層的索引try {loadingIndex = layer.load(1);// 使用 fetch API 發送 GET 請求const response = await fetch(downloadUrl, {method: 'GET', // 后端是 @GetMapping,所以前端也用 GETcache: 'no-cache', // 根據你的后端設置,這里也禁用緩存});// 檢查響應是否成功if (!response.ok) {// 如果服務器返回錯誤狀態 (如 404, 500)// 你可以根據 response.status 和 response.statusText 來處理不同類型的錯誤const errorText = await response.text(); // 嘗試獲取錯誤信息文本throw new Error(`服務器錯誤: ${response.status} ${response.statusText}. ${errorText}`);}// 從響應頭中獲取文件名// 后端設置了 Content-Disposition: attachment; filename=...const contentDisposition = response.headers.get('content-disposition');let filename = `image_${imageId}.png`; // 默認文件名,如果無法從頭部獲取if (contentDisposition) {const filenameMatch = contentDisposition.match(/filename\*?=['"]?(?:UTF-\d['"]*)?([^;"\n]*)/i);if (filenameMatch && filenameMatch[1]) {filename = decodeURIComponent(filenameMatch[1]);}}// 將響應體轉換為 Blob 對象const blob = await response.blob();// 創建一個指向 Blob 的 URLconst objectUrl = window.URL.createObjectURL(blob);// 創建一個臨時的 <a> 標簽用于觸發下載const link = document.createElement('a');link.href = objectUrl;link.setAttribute('download', filename); // 設置下載的文件名document.body.appendChild(link);// 觸發點擊link.click();// 清理:移除 <a> 標簽并釋放 Object URLdocument.body.removeChild(link);window.URL.revokeObjectURL(objectUrl);// 如果你使用了 parent.layer.alert,可以在這里提示成功if (parent && parent.layer) {parent.layer.alert("圖片下載成功!");}} catch (error) {console.error('下載圖片時發生錯誤:', error);// 如果你使用了 parent.layer.alert,可以在這里提示錯誤if (parent && parent.layer) {parent.layer.alert(`連接或下載錯誤: ${error.message}`);}throw error; // 重新拋出錯誤,以便調用者可以進一步處理}finally {layer.close(loadingIndex);}
}// 如果你仍然想在類似 $.ajax 的結構中使用,可以這樣包裝:
function triggerDownloadWithAjaxLikeStructure(imageId) {// 這里不再需要 $('#signupForm').serialize(),因為 ID 是直接傳遞的// 也不再需要 type: "POST",因為下載是 GET// async: false 非常不推薦,fetch 默認就是異步的,應該使用 Promise 處理downloadImage(imageId).then(() => {// 成功回調,提示已經在 downloadImage 函數內部處理// 你可以在這里添加額外的成功邏輯console.log('圖片下載流程成功完成。');}).catch(error => {// 錯誤回調,提示已經在 downloadImage 函數內部處理// 你可以在這里添加額外的錯誤處理邏輯console.error('圖片下載流程發生錯誤。', error);});
}
triggerDownloadWithAjaxLikeStructure(id)