如何在Linux环境下不依赖win32库用Python将Excel工作表转为PNG
解决方案
方案1:纯Python实现(手动重现表格与图表)
适合图表类型简单、无需完全还原Excel样式的场景,依赖openpyxl和matplotlib两个库,无额外系统依赖。
步骤与代码示例
- 安装依赖:
pip install openpyxl matplotlib
- 示例代码(以包含表格和柱状图的工作表为例):
from openpyxl import load_workbook import matplotlib.pyplot as plt from matplotlib.table import Table # 加载目标Excel文件 wb = load_workbook("your_file.xlsx") ws = wb.active # 1. 读取表格数据(根据实际数据范围调整行/列参数) table_range = ws.iter_rows(min_row=1, max_row=6, min_col=1, max_col=4, values_only=True) table_data = [list(row) for row in table_range] # 2. 解析图表信息(假设工作表中第一个图表为柱状图) chart = ws._charts[0] # 获取分类标签与数值数据 category_cells = ws[chart.series[0].categories.ref] categories = [cell.value for cell in category_cells] value_cells = ws[chart.series[0].values.ref] values = [cell.value for cell in value_cells] # 3. 创建画布,同时绘制表格与图表 fig, (ax_table, ax_chart) = plt.subplots(2, 1, figsize=(12, 9), dpi=150) # 绘制表格:隐藏坐标轴,添加表格元素 ax_table.axis("off") table = Table(ax_table, bbox=[0, 0, 1, 1]) row_height = 1 / len(table_data) col_width = 1 / len(table_data[0]) for i, row in enumerate(table_data): for j, val in enumerate(row): table.add_cell(i, j, col_width, row_height, text=val, loc="center") ax_table.add_table(table) # 绘制图表:还原图表标题、坐标轴标签 ax_chart.bar(categories, values) ax_chart.set_title(chart.title.text, fontsize=12) ax_chart.set_xlabel(chart.x_axis.title.text, fontsize=10) ax_chart.set_ylabel(chart.y_axis.title.text, fontsize=10) # 调整布局避免元素重叠 plt.tight_layout() # 保存为PNG plt.savefig("output.png") plt.close()
方案2:基于LibreOffice的完整还原方案
适合需要1:1还原Excel格式(包括复杂图表、单元格样式)的场景,需依赖Linux系统下的LibreOffice工具。
步骤与代码示例
- 安装系统依赖(Debian/Ubuntu系):
sudo apt update && sudo apt install libreoffice libreoffice-calc poppler-utils
- 安装Python依赖:
pip install pdf2image
- 示例代码:
import subprocess from pdf2image import convert_from_path import os # 配置文件路径 excel_path = "your_file.xlsx" temp_pdf = "temp_convert.pdf" output_png = "full_sheet.png" # 调用LibreOffice将Excel转为PDF(无头模式) subprocess.run( ["libreoffice", "--headless", "--convert-to", "pdf", excel_path, "--outdir", "./"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) # 将PDF转为PNG(仅保留第一页,即目标工作表) pages = convert_from_path(temp_pdf, dpi=300) pages[0].save(output_png, "PNG") # 清理临时PDF文件 os.remove(temp_pdf)
说明
- LibreOffice的无头模式可在后台完成转换,完全适配Linux环境
- 转换后的PNG会完整保留Excel中的所有元素,包括图表样式、单元格格式、合并单元格等
内容的提问来源于stack exchange,提问作者NickTay
相关产品推荐
相关产品推荐

