Django使用Google云存储中的Openpyxl打开EXCEL.xlsx [英] Django open excel.xlsx with openpyxl from Google Cloud Storage
问题描述
我需要在Google云存储上从我的存储桶中打开一个.xlsx文件,问题是我得到的是:FileNotFoundError at/api/fi ha-excel
[Errno 2]没有这样的文件或目录:‘ficha.xlsx’
这些是我的存储桶中的设置。
UPLOAD_ROOT = 'reportes/'
MEDIA_ROOT = 'reportes'
这些是路由存储桶/reportes/fi ha.xlsx
这是我的Get函数的代码:
directorio = FileSystemStorage("/reportes").base_location
os.makedirs(directorio, exist_ok=True)
# read
print("Directorios: ", directorio)
plantilla_excel = openpyxl.load_workbook(f"{directorio}/ficha.xlsx")
print(plantilla_excel.sheetnames)
currentSheet = plantilla_excel['Hoja1']
print(currentSheet['A5'].value)
该路径有什么问题?我想不通了。
推荐答案
以下解决方案不使用Django文件存储/存储类。它使用Openpyxl从Google存储的云存储存储桶中打开一个.xlsx文件。
摘要:
我将Excel文件上传到GCS上,通过BytesIO使用Openpyxl读取Blob数据,并使用.save()方法将数据保存在工作簿中。
要遵循的步骤:
创建Google云存储存储桶。为它选择一个全局唯一的名称。保留默认设置,最后输入Create。
从您的本地系统中选择一个Excel文件,并使用上传文件选项将其上传到存储桶中。 一旦您的存储桶中有了Excel文件,请执行以下步骤:进入Google Cloud Platform创建服务账号(API)。单击 导航菜单>;API&;服务&>凭证进入屏幕。 然后单击"管理服务帐户"。
在下一个屏幕上,单击"创建服务帐户"。
输入每个项目的服务帐户的详细信息。
在下一节中,您将为云存储创建一个角色。选 存储管理员(完全权限)。
单击您创建的服务帐户,然后在密钥中单击添加密钥
字段,然后选择创建新密钥。
选择JSON作为键类型,并创建";it。由于JSON文件是 下载到本地存储中,在下一项中使用JSON文件 并通过Python操作云存储。
我们将在云中安装此项目所需的库 外壳首先,使用pip安装Google云存储库 安装即可访问云硬盘:
pip install google-cloud-storage
使用:
安装Openpyxlpip install openpyxl
在Cloud编辑器中使用您选择的名称创建一个文件夹(Excel)。 在其中创建文件:
main.py JSON密钥文件(下载到本地存储的那个文件,复制 文件放入此文件夹)
Excel Main.py .json
在main.py文件中编写以下代码行:
from google.cloud import storage
import openpyxl
import io
#Create a client instance for google cloud storage
client = storage.Client.from_service_account_json('●●●●●●●●●●.json') //The path to your JSON key file which is now
#Get an instance of a bucket
bucket = client.bucket(‘bucket_name’) //only the bucketname will do, full path not necessary.
##Get a blob instance of a file
blob = bucket.blob(‘test.xlsx') // test.xlsx is the excel file I uploaded in the bucket already.
buffer = io.BytesIO()
blob.download_to_file(buffer)
wb = openpyxl.load_workbook(buffer)
wb.save('./retest.xlsx')
您将看到在Cloud Editor的同一文件夹中创建了一个文件‘reest.xlsx’。
这篇关于Django使用Google云存储中的Openpyxl打开EXCEL.xlsx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!