python实现Excel转图片

[复制链接]
发表于 2025-12-2 15:13:03 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
目次
利用spire.xls库
利用excel2img库


利用spire.xls库

安装:pip install spire.xls -i https://pypi.tuna.tsinghua.edu.cn/simple
支持选择行和列截图,欠好的一点就是商业库,转出来的图片有水印。

  1. from spire.xls import Workbook
  2. def excel_image(excel_file):
  3.     '''
  4.     ToImage 中可指定需要生成图片的行和列
  5.     :param excel_file:
  6.     :return:
  7.     '''
  8.     save_image_path = rf'{excel_file.split('.')[0]}.png'
  9.     work = Workbook()
  10.     work.LoadFromFile(excel_file)
  11.     # 指定第一张表生成数据
  12.     # sheet = work.Worksheets.get_Item(0)
  13.     # # 移除页边距
  14.     # pagesetup = sheet.PageSetup
  15.     # pagesetup.TopMargin = 0
  16.     # pagesetup.BottomMargin = 0
  17.     # pagesetup.LeftMargin = 0
  18.     # pagesetup.RightMargin = 0
  19.     # image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn)
  20.     # image.Save(save_image_path)
  21.     # work.Dispose()
  22.     # 将所有表单生成图片
  23.     for i, sheet in enumerate(work.Worksheets):
  24.         # image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn)
  25.         image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, 5, 2)
  26.         image.Save(rf'{excel_file.split('.')[0]}{i}.png')
  27.     work.Dispose()
复制代码
利用excel2img库

安装:pip install excel2img -i https://pypi.tuna.tsinghua.edu.cn/simple
  1. import excel2img
  2. def out_img(excel_file, sheet_list, output_dir):
  3.     try:
  4.         print("截图中,请等待...")
  5.         for sheet in sheet_list:
  6.             excel2img.export_img(excel_file, f"{output_dir}/{sheet}.png", sheet)
  7.         print("截图完成!")
  8.     except Exception as e:
  9.         print("截图失败!", e)
  10. if __name__ == '__main__':
  11.     file_name = r'C:\Users\Administrator\Desktop\test\成绩表.xls'
  12.     sheet_list = ['Sheet1', 'Sheet2']  # 需要截图sheet名称
  13.     output_dir = r'C:\Users\Administrator\Desktop'
  14.     out_img(file_name, sheet_list, output_dir)
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表