python - pandas 和 openpyxl 在添加工作表时创建损坏的 excel 文件
问题描述
我正在尝试使用创建一个 excel 文件pandas.DataFrame.to_excel
,向其中添加一张或多张工作表并更改单元格的格式。我找到了一种方法来做到这一点,但最终总是有一个损坏的 excel 文件。我想我以某种错误的方式使用了 writer 对象。
import os
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Alignment
def excelcellwitdh(wb, sheet, cols, exclude, align):
# function that adjusts cell width and centers cells
ws = wb[sheet]
count = -1
for column in ws.columns:
count +=1
if cols[count] not in exclude:
length = max(len(str(cell.value)) for cell in column)
ws.column_dimensions[column[0].column_letter].width = length*1.15
if align == "center":
for cell in column:
cell.alignment = Alignment(horizontal='center')
directory = "Path"
# provide directory here which will contain the data for my DataFrames
outputfile = os.path.join(directory, "Output_"+directory.split("\\")[-1]+".xlsx")
# this file does not exist yet
df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],
index=['row 1', 'row 2'],
columns=['col 1', 'col 2'])
df2 = pd.DataFrame(columns= ["D", "E", "F"])
# create df1 and df2 (For simplicity I created two dummy DataFrames)
df1.to_excel(outputfile, sheet_name='1', index = None)
# create excel file with df1
wb = load_workbook(outputfile)
writer = pd.ExcelWriter(outputfile, engine='openpyxl')
# create writer object
writer.book = wb
df2.to_excel(writer, sheet_name = '2', index = None)
# add df2 to excel sheet
excelcellwitdh(wb, "1", df1.columns, exclude = ['col 2'], align = "center")
excelcellwitdh(wb, "2", df2.columns, exclude = ["D"], align = "left")
# format cells
writer.save()
writer.close()
使用时
with pd.ExcelWriter(outputfile) as writer:
df1.to_excel(writer, sheet_name='1')
df2.to_excel(writer, sheet_name='2')
我得到一个未损坏的文件,但我不能再使用我的功能了。我在这里想念什么?
解决方案
推荐阅读
- tcl - thread::join 如何运行脚本?
- php - 关于 make:crud 和在 Symfony flex 路由中使用 yaml
- ios - 屏幕底部按钮:iPhone X 与普通屏幕
- ios - UserActivity ReferrerURL 为零
- c - else 语句导致 c 13 中预期的标识符
- c# - WebAPI 在开头添加类标题
- javascript - yarn 无法使用 node 12.1.0 构建 node-sass
- typescript - Typescript编译文件找不到模块
- git - 如何忽略为 git 管理的文件或文件夹历史记录?
- kotlin - 如何使用 detekt 及其访问者浏览给定 Kotlin 文件的 AST?