You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Notebook调用Azure存储容器将.xls转换为.xlsx?

Python Notebook实现Azure存储容器中.xls转.xlsx格式转换

步骤1:安装依赖库

在Notebook中执行以下命令安装所需工具包:

pip install azure-storage-blob pandas xlrd openpyxl
  • azure-storage-blob:用于操作Azure Blob存储
  • pandas:处理Excel文件的核心库
  • xlrd:支持读取.xls格式文件
  • openpyxl:支持写入.xlsx格式文件

步骤2:编写转换代码

将以下代码复制到Notebook单元格中,替换占位符为你的Azure存储信息:

import os
import pandas as pd
from azure.storage.blob import BlobServiceClient

# 配置Azure存储信息
storage_account_name = "你的存储账户名称"
storage_account_key = "你的存储账户密钥"
container_name = "目标容器名称"
source_blob_name = "要转换的.xls文件名(比如test.xls)"
target_blob_name = "转换后的.xlsx文件名(比如test.xlsx)"

# 初始化Blob服务客户端
connect_str = f"DefaultEndpointsProtocol=https;AccountName={storage_account_name};AccountKey={storage_account_key};EndpointSuffix=core.windows.net"
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_client = blob_service_client.get_container_client(container_name)

# 临时文件路径(Notebook本地临时存储)
local_xls_path = f"./temp_{source_blob_name}"
local_xlsx_path = f"./temp_{target_blob_name}"

try:
    # 1. 从Azure容器下载.xls文件到本地
    source_blob_client = container_client.get_blob_client(source_blob_name)
    with open(local_xls_path, "wb") as download_file:
        download_file.write(source_blob_client.download_blob().readall())
    print(f"已下载文件:{source_blob_name}")

    # 2. 格式转换:.xls转.xlsx
    df = pd.read_excel(local_xls_path, engine="xlrd")
    df.to_excel(local_xlsx_path, engine="openpyxl", index=False)
    print("格式转换完成")

    # 3. 将转换后的.xlsx文件上传回Azure容器
    target_blob_client = container_client.get_blob_client(target_blob_name)
    with open(local_xlsx_path, "rb") as upload_file:
        target_blob_client.upload_blob(upload_file, overwrite=True)
    print(f"已上传转换后的文件:{target_blob_name}")

finally:
    # 清理本地临时文件
    if os.path.exists(local_xls_path):
        os.remove(local_xls_path)
    if os.path.exists(local_xlsx_path):
        os.remove(local_xlsx_path)
    print("临时文件已清理")

注意事项

  • 确保你的Azure存储账户有Blob数据读取和写入权限
  • 如果.xls文件包含复杂格式(比如宏、合并单元格),pandas可能无法完全保留格式,这类场景建议使用win32com.client(仅Windows环境支持)或pywin32替代pandas
  • 若批量转换,可以遍历容器内所有.xls文件,循环执行上述逻辑

内容的提问来源于stack exchange,提问作者Noobiee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 12:44:54