【问题标题】:How to convert a excel file to base64 and then convert base64 back to excel in python?如何将excel文件转换为base64,然后在python中将base64转换回excel?
【发布时间】:2020-05-20 04:09:43
【问题描述】:

如何在python中将excel文件转换为base64,然后再将base64转换回excel? 我打算将 Base64 数据存储在数据库中并按需检索并转换回 excel?有什么帮助吗?

【问题讨论】:

  • 我认为你很难只在内存中这样做。 ..我怀疑成功的最简单途径是将excel文件保存到磁盘,然后将文件转换为base64并保存在您的数据库中...取出时,对其进行解码,写入临时文件,然后读入临时文件...将文件保存在磁盘上并在数据库中包含指向该文件的指针可能更有意义
  • 嗨 Joran,我不能将它存储在本地,但是如何在 base64 中对文件进行编码然后解码呢?你能给我一个python的例子吗?
  • base64.b64encode(open("some.xlsx","rb").read()) ...我不明白您如何无法将其保存在本地...但没关系,我不需要
  • 这看起来不错,我也在写一个自动化脚本,所以不能在本地存储任何东西:)

标签: python excel pandas postgresql base64


【解决方案1】:
import base64

def open_target_file(target_path):
    with open(target_path,"rb") as excel_file:
        return excel_file.read()

def encode_file(excel_file):
    return base64.b64encode(excel_file)

def decode_file():
    return base64.b64decode(excel_file)

your_excel_path = ""
destiny_path = ""

excel_file = open_target_file()
encoded_excel = encode_file(excel_file)
decoded_excel = decode_file(encoded_excel)

with open(destiny_path, "wb") as decoded_file:
    decoded_file.write(decoded_excel)

这样的事情应该可以工作。

【讨论】:

  • 嗨 Joao,这可能会有所帮助,当我解码 excel 文件时它仍然是字符串,我应该如何将其转换回 excel?
  • 如果将二进制文件等存储在您的基础中,并且在解码相同的二进制文件后,您将不会有任何问题!
  • 不错的答案 :) 应该可以做到这一切...但是您需要将文件路径更改为“”以外的其他内容我认为...您可能是能够使用 stringIO 来避免一起写入磁盘......也许......也许很大
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-06
  • 2015-04-29
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多