【问题标题】:Formatting multiple worksheets using xlsxwriter使用 xlsxwriter 格式化多个工作表
【发布时间】:2015-10-29 14:19:10
【问题描述】:

如何使用 Python 中的xlsxwriter 库将相同的格式复制到同一 Excel 文件的不同工作表中?

我试过的代码是:

import xlsxwriter

import pandas as pd
import numpy as np

from xlsxwriter.utility import xl_rowcol_to_cell

df = pd.DataFrame()
df = pd.read_excel('TrendAnalysis.xlsx')



# Create a Pandas Excel writer using XlsxWriter as the engine.
# Save the unformatted results
writer_orig = pd.ExcelWriter('TrendAnalysis.xlsx', engine='xlsxwriter')
df.to_excel(writer_orig, index=True)
writer_orig.save()

work = ["isu-wise", "ISU-BFS", "ISU-CPG", "ISU-ER", "ISU-GE", "ISU-GOV Domestic", "ISU-GOV Overseas", "ISU-HC"]
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('TrendAnalysis.xlsx', engine='xlsxwriter')
for i in range(0,len(work)):
    df.to_excel(writer, index=True, sheet_name=work[i])

    # Get access to the workbook and sheet
    workbook = writer.book
    worksheet = writer.sheets[work[i]]

    print worksheet
    # We need the number of rows in order to place the totals
    number_rows = len(df.index)

    # Total formatting
    total_fmt = workbook.add_format({'align': 'right', 'num_format': '#,##0',
                                    'bold': True, 'bottom':6})

    # Add total rows
    for column in range(1,3):
        # Determine where we will place the formula
        cell_location = xl_rowcol_to_cell(number_rows+1, column)
        # Get the range to use for the sum formula
        start_range = xl_rowcol_to_cell(1, column)
        end_range = xl_rowcol_to_cell(number_rows, column)
        # Construct and write the formula
        formula = "=SUM({:s}:{:s})".format(start_range, end_range)
        worksheet.write_formula(cell_location, formula, total_fmt)

    # Add a total label
    worksheet.write_string(number_rows+1, 0, "Total",total_fmt)
    i+=1

writer.save()
workbook.close()

它会多次创建同一张工作表。不导航和工作簿第一个之后的工作表。代码没有错误,否则会进行所需的格式化。

【问题讨论】:

  • 您能否澄清一下问题究竟是什么?
  • 你正在格式化声明对我来说很合适。看起来您正在向 excel 文件中的每个工作表写入相同的 DataFrame。最后一个df 声明是df = pd.read_excel('TrendAnalysis.xlsx')
  • 我的 EXCEL 文件有多个工作表。我正在尝试使用循环并以相同的方式格式化所有工作表。但每次它只访问第一个工作表。能否请你帮忙。?哦,我正在尝试编辑同一工作簿/excel 文件的工作表,这就是为什么我的 df 声明引用 TrendAnalysis.xlsx
  • 您找到解决方案了吗?

标签: python python-2.7 xlsxwriter


【解决方案1】:

可能为时已晚,但这是我为此所做的。在我的示例中,我有 2 个 DataFrame,我想冻结窗格,为每一列添加过滤器,并格式化保存在同一个 excel 文件中的两个工作表的标题。

writer = pd.ExcelWriter(path_of_excel_file+'output.xlsx')
sheets_in_writer=['Sheet1','sheet2']
data_frame_for_writer=[df1, df2]

for i,j in zip(data_frame_for_writer,sheets_in_writer):
    i.to_excel(writer,j,index=False)

### Assign WorkBook
workbook=writer.book
# Add a header format
header_format = workbook.add_format({'bold': True,'text_wrap': True,'size':10,
                                                      'valign': 'top','fg_color': '#c7e7ff','border': 1})
### Apply same format on each sheet being saved
for i,j in zip(data_frame_for_writer,sheets_in_writer):
    for col_num, value in enumerate(i.columns.values):
        writer.sheets[j].write(0, col_num, value, header_format)
        writer.sheets[j].autofilter(0,0,0,i.shape[1]-1)
        writer.sheets[j].freeze_panes(1,0)
writer.save()

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 2018-12-26
    • 2017-02-15
    • 2017-02-16
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多