在各種情況下,需要將 Excel 電子表格嵌入到 Web 或桌面應用程序中。在這種情況下的解決方案之一是將 Excel 工作表轉換爲圖像格式。在本文中,將學習如何在 Python中將Excel XLSX 或 XLS 轉換爲 PNG、JPEG、SVG 或其他圖像。
- 在 Python 中將 Excel 轉換爲圖像
- 在 Python 中將 Excel 轉換爲 SVG
爲了將 Excel 的 XLSX 或 XLS 文件轉換爲圖像格式,我們將使用Aspose.Cells for Python via Java它是一個電子表格操作 API,可讓您創建、修改或轉換 Excel 文件。你可以下載Aspose.Cells for Python
Aspose.Cells for Python via Java 支持將 Excel 文件轉換爲以下圖像格式:
- EMF
- WMF
- JPEG
- PNG
- BMP
- GIF
- TIFF
- SVG
- GLTF
- PICT
- SVM
- Office Compatible EMF
在 Python 中將 Excel 轉換爲圖像
以下是將 Excel 文件轉換爲圖像格式,即 PNG、JPEG 等的步驟。
- 使用Workbook類加載 Excel 文件
- 創建ImageOrPrintOptions類的實例並指定輸出圖像格式。
- 使用Workbook.getWorksheets().get(index)方法訪問要轉換的工作表。
- 創建一個SheetRender對象並使用Worksheet和ImageOrPrintOptions對象對其進行初始化。
- 使用SheetRender.toImage(pageIndex, fileName)方法將 Excel 工作表的每一頁保存爲圖像。
以下代碼示例展示瞭如何在 Python 中將 Excel 工作表轉換爲 PNG 圖像。
# load the Excel workbook workbook = Workbook("Book1.xlsx") # create image options imgOptions = ImageOrPrintOptions() imgOptions.setSaveFormat(SaveFormat.SVG) # load the worksheet to be rendered sheet = workbook.getWorksheets().get(0) # create sheet render object sr = SheetRender(sheet, imgOptions) # convert sheet to PNG image for j in range(0, sr.getPageCount()): sr.toImage(j, "WorksheetToImage-out%s" %(j) + ".png")
在 Python 中將 Excel 轉換爲 SVG
以下是在 Python 中將 Excel 文件轉換爲 SVG 的步驟。
- 使用Workbook類加載 Excel 文件。
- 創建ImageOrPrintOptions類的實例並指定輸出圖像格式。
- 使用Workbook.getWorksheets().getCount()方法遍歷 Excel 文件中的工作表。
- 在每次迭代中,執行以下操作:
- 創建一個SheetRender對象並使用Worksheet和ImageOrPrintOptions對象對其進行初始化。
- 使用SheetRender.toImage(pageIndex, fileName)方法將 Excel 工作表的每一頁保存爲 SVG 。
以下代碼示例展示瞭如何在 Python 中將 Excel 轉換爲 SVG。
# load the Excel workbook workbook = Workbook("Book1.xlsx") # create image options imgOptions = ImageOrPrintOptions() imgOptions.setSaveFormat(SaveFormat.SVG) # get sheet count sheetCount = workbook.getWorksheets().getCount() # loop through the sheets for i in range(0, sheetCount): sheet = workbook.getWorksheets().get(i) # convert each sheet to SVG sr = SheetRender(sheet, imgOptions) for j in range(0, sr.getPageCount()): sr.toImage(j, sheet.getName() + "%s" % j + "_out.svg")
如果您有任何疑問或需求,請隨時加入Aspose技術交流羣(761297826),我們很高興爲您提供查詢和諮詢。