Sam*_*fer 5 python pandas openpyxl xlsxwriter
我想格式化A1:E14为美元、F1:K14百分比和A15:Z1000美元。有没有办法在 XlsxWriter 中做到这一点?
我知道如何将完整列格式化为 Dollars/Percentages,但我不知道如何格式化列的一部分——无论我最后做什么都会覆盖 Columns F:K。
数据从大熊猫开始,很高兴在那里解决问题。以下似乎不起作用:
sheet.set_column('A1:E14', None, money_format)
Run Code Online (Sandbox Code Playgroud)
更多代码:
with pd.ExcelWriter(write_path) as writer:
book = writer.book
money_fmt = book.add_format({'num_format': '$#,##0'})
pct_fmt = book.add_format({'num_format': '0.00%'})
# call func that creates a worksheet named total with no format
df.to_excel(writer, sheet_name='Total', startrow=0)
other_df.to_excel(writer, sheet_name='Total', startrow=15)
writer.sheets['Total'].set_column('A1:E14',20, money_fmt)
writer.sheets['Total'].set_column('F1:K14',20, pct_fmt)
writer.sheets['Total'].set_column('F15:Z1000', 20, money_fmt)
Run Code Online (Sandbox Code Playgroud)
我看不到仅使用 Pandas 来实现每个单元格格式的方法xlsxwriter,但可以使用openpyxl以下方法在单独的步骤中应用格式:
import openpyxl\n\ndef write_format(ws, cell_range, format):\n for row in ws[cell_range]:\n for cell in row:\n cell.number_format = format\n\nsheet_name = "Total"\n\nwith pd.ExcelWriter(write_path) as writer:\n write_worksheet(df, writer, sheet_name=sheet_name) \n\nwb = openpyxl.load_workbook(write_path)\nws = wb.get_sheet_by_name(sheet_name) \n\nmoney_fmt = \'$#,##0_-\'\npct_fmt = \'0.00%\'\n\nwrite_format(ws, \'A1:G1\', money_fmt)\nwrite_format(ws, \'A1:E14\', money_fmt)\nwrite_format(ws, \'F1:K14\', pct_fmt)\nwrite_format(ws, \'F15:Z1000\', money_fmt) \n\nwb.save(write_path) \nRun Code Online (Sandbox Code Playgroud)\n\n当尝试使用 时xlsxwriter,它总是会覆盖 Pandas 中的现有数据。但是,如果随后让 Pandas 重写数据,它就会覆盖任何应用的格式。似乎没有任何方法可以在不覆盖内容的情况下将格式应用于现有单元格。例如,write_blank()函数指出:
\n\n此方法用于向不包含字符串或数字值的单元格添加格式。
\n
| 归档时间: |
|
| 查看次数: |
2116 次 |
| 最近记录: |