Streamlit能否正常展示Excel工作表中的表格、评论及图表内容?
Streamlit 展示Excel全内容解决方案
下面提供两种可落地的实现路径,可根据部署环境选择:
方案1:分模块提取原生渲染(无需转HTML,兼容性最高)
直接单独提取Excel内的三类内容,用Streamlit原生组件渲染,不存在资源加载异常问题。
- 依赖安装:需提前安装
pandasopenpyxlxlwingsstreamlit四个核心库 - 表格渲染
import pandas as pd import streamlit as st # 读取工作表表格内容 df = pd.read_excel("目标文件.xlsx", sheet_name="指定工作表") st.dataframe(df, use_container_width=True)
- 批注提取展示
from openpyxl import load_workbook wb = load_workbook("目标文件.xlsx") ws = wb["指定工作表"] comment_list = [] for row in ws.iter_rows(): for cell in row: if cell.comment: comment_list.append(f"单元格 {cell.coordinate}:{cell.comment.text}") # 折叠展示所有批注 if comment_list: with st.expander("查看工作表全部批注"): for item in comment_list: st.write(item)
- 图表渲染
import xlwings as xw from io import BytesIO from PIL import Image # 后台启动Office进程读取图表 with xw.App(visible=False) as app: wb = app.books.open("目标文件.xlsx") ws = wb.sheets["指定工作表"] for index, chart in enumerate(ws.charts): # 导出图表为图片字节流 chart.api.CopyPicture() img = Image.open(BytesIO(app.api.Selection.Paste())) st.image(img, caption=f"图表 {index+1}") wb.close()
方案2:修复转HTML方案(保留原Excel布局)
之前图表无法显示是因为转HTML时图表资源为外部独立文件,组件加载时找不到路径,调整为导出内嵌资源的单HTML文件即可解决:
import streamlit.components.v1 as components import xlwings as xw with xw.App(visible=False) as app: wb = app.books.open("目标文件.xlsx") ws = wb.sheets["指定工作表"] # 导出为内嵌所有资源的单HTML文件,FileFormat=44对应带内嵌资源的HTML格式 ws.api.SaveAs("temp_excel.html", FileFormat=44) wb.close() # 加载HTML内容 with open("temp_excel.html", "r", encoding="utf-8") as f: html_content = f.read() components.html(html_content, height=800, scrolling=True)
注意:xlwings依赖本地安装的Office/WPS环境,无桌面环境的Linux服务器可安装LibreOffice,执行命令libreoffice --convert-to html --embed-images 目标文件.xlsx 直接生成内嵌资源的HTML文件,无需调用xlwings
内容的提问来源于stack exchange,提问作者Eugenirfan
相关产品推荐
相关产品推荐

