在 Azure 中使用 Python 调整 Excel 文件 sheet 列的大小
Resize Excel file sheet columns using Python in Azure
在 Azure 中使用 Blob 存储时,我无法调整 Python 的 excel 工作表中列的大小。让我知道我做错了什么。以下是相关代码片段-
def resize_columns(df, data_val, sheet_name):
wb = openpyxl.load_workbook(data_val)
worksheet = wb[sheet_name]
cols = list(df.columns)
count = 0
for column in worksheet.columns:
length = max(df[cols[count]].astype(str).str.len().max(), len(cols[count]))*1.25
length = length if length <= 16 else 16
worksheet.column_dimensions[column[0].column_letter].width = length
count += 1
return data_val
connect_str = "..."
blob_client = blob_service_client.get_blob_client(container=new_container_name, blob=file_name)
data_val = io.BytesIO()
writer = pd.ExcelWriter(data_val, engine="openpyxl")
mpm_summary = pd.DataFrame({"one_val": [1, 2]})
mpm_summary.to_excel(writer, sheet_name="A", index=False)
mpm_summary = pd.DataFrame({"two_val00000000000000000000000000000000000000": [3, 4], "three_val": [5,6]})
mpm_summary.to_excel(writer, sheet_name="B", index=False)
writer.save()
data_val = resize_columns(mpm_summary, data_val, "B")
blob_client.upload_blob(data_val.getvalue(), overwrite=True)
非常感谢您的帮助。谢谢
而不是用
再次加载工作簿wb = openpyxl.load_workbook(data_val)
您可以只使用编写器指针本身来访问工作表,进行更改并在上传 blob 之前保存它。
def resize_columns(writer,df, data_val, sheet_name):
#wb = openpyxl.load_workbook(data_val)
worksheet = writer.book[sheet_name] #wb[sheet_name]
cols = list(df.columns)
count = 0
for column in worksheet.columns:
length = max(df[cols[count]].astype(str).str.len().max(), len(cols[count]))*1.25
length = length if length <= 16 else 16
worksheet.column_dimensions[column[0].column_letter].width = length+0.78
count += 1
return data_val
blob_client = blob_service_client.get_blob_client(container=container_name, blob=file_name)
data_val = io.BytesIO()
writer = pd.ExcelWriter(data_val, engine="openpyxl")
mpm_summary = pd.DataFrame({"one_val": [1, 2]})
mpm_summary.to_excel(writer, sheet_name="A", index=False)
mpm_summary = pd.DataFrame({"two_val00000000000000000000000000000000000000": [3, 4], "three_val": [5,6]})
mpm_summary.to_excel(writer, sheet_name="B", index=False)
data_val = resize_columns(writer,mpm_summary, data_val, "B")
writer.save()
blob_client.upload_blob(data_val.getvalue(), overwrite=True)
请注意 openpyxl 宽度与宽度之间所需的轻微 difference/correction 系数。 excel 列宽。因此,您的倍增因子或偏移量可能需要微调。 https://foss.heptapod.net/openpyxl/openpyxl/-/issues/293
openpyxl - adjust column width size