如何在Java中轉換Excel文件到圖像?

Excel電子表格被廣泛用於存儲,組織和分析數據。但是,不能將Excel工作簿或工作表直接嵌入到Web或桌面應用程序中。合適的選項之一是將工作表轉換爲圖像或HTML格式。在本文中,將學習如何使用Java將Excel XLSX / XLS文件轉換爲PNG,JPEG,BMP和其他圖像格式。

  • 將Excel文件轉換爲圖像
  • Excel到圖像轉換的附加選項

Aspose.Cells for Java是功能強大的電子表格處理API,可將工作表高質量轉換爲PNG,JPEG,BMP和其他流行的圖像格式。點擊獲取最新版

將Excel XLSX轉換爲Java中的圖像

Aspose.Cells for Java支持將Excel文件轉換爲以下圖像格式:

  • EMF
  • WMF
  • JPEG
  • PNG
  • BMP
  • GIF
  • TIFF
  • SVG
  • GLTF
  • PICT
  • SVM
  • Office Compatible EMF

以下是將工作表轉換爲PNG圖像的API引用步驟。

  • 使用工作簿 類加載Excel文件。
  • 創建ImageOrPrintOptions類的實例。
  • 獲取要轉換爲工作表對象的工作表。
  • 創建一個SheetRender對象,並使用Worksheet和ImageOrPrintOptions對象對其進行初始化。
  • 轉換工作表並使用SheetRender.toImage(int,String)方法保存圖像文件。

下面的代碼示例演示如何使用Java將Excel XLSX文件轉換爲圖像。

// Load Excel file
Workbook workbook = new Workbook("workbook.xlsx");

// Create an object of ImageOrPrintOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();

// Set the output image type
imgOptions.setImageType(ImageType.PNG);

// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

// Create a SheetRender object for the target sheet
SheetRender sr = new SheetRender(sheet, imgOptions);

for (int page = 0; page < sr.getPageCount(); page++) { // Generate an image for the worksheet sr.toImage(page, "image" + page + ".png"); }

Excel File

Excel to Image Java

Converted PNG

XLSX to PNG java

Excel到圖像轉換的附加選項

Aspose.Cells for Java還提供了其他選項,以自定義XLSX進行圖像轉換。例如,您可以指定網格線的樣式,每張紙渲染一張圖像,等等。該ImageOrPrintOptions類用於設置這些選項。下面的代碼示例演示如何在Excel中使用ImageOrPrintOptions類進行圖像轉換。

// Load Excel file
Workbook workbook = new Workbook("workbook.xlsx");

// Create an object of ImageOrPrintOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();

// Set the image type
imgOptions.setImageType(ImageType.PNG);

// Set one page per sheet rendering
imgOptions.setOnePagePerSheet(true);

// Set gridline
imgOptions.setGridlineType(GridlineType.DOTTED);

// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

// Create a SheetRender object for the target sheet
SheetRender sr = new SheetRender(sheet, imgOptions);

for (int page = 0; page < sr.getPageCount(); page++) {
	// Generate an image for the worksheet
	sr.toImage(page, "image" + page + ".png");
}

如果您有任何疑問或需求,請隨時加入Aspose技術交流羣(761297826),我們很高興爲您提供查詢和諮詢

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章