我使用xlwt
在 excel 中创建表格。在 excel 中,有一个功能格式为表,这使得该表具有每列的自动过滤器。有没有办法使用python做到这一点?
答案 0 :(得分:4)
好的,在搜索网络后,我意识到使用xlwt
时无法做到这一点,但XlsxWriter
可能会非常简单方便。< / p>
答案 1 :(得分:0)
您也可以使用Pandas。这是一个示例:
import pandas as pd
df = pd.DataFrame({
'city': ['New York', 'London', 'Prague'],
'population': [19.5, 7.4, 1.3],
'date_of_birth': ['1625', '43', 'early 8th century'],
'status_of_magnetism': ['nice to visit', 'nice to visit', 'definetely MUST visit']
})
# initialize ExcelWriter and set df as output
writer = pd.ExcelWriter(r'D:\temp\sample.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Cities', index=False)
# worksheet is instance of Excel sheet "Cities" - used for inserting the table
worksheet = writer.sheets['Cities']
# workbook is instance of whole book - used i.e. for cell format assignment
workbook = writer.book
然后通过workbook.add_format定义单元格的格式(即旋转文本,设置垂直和水平对齐)
header_cell_format = workbook.add_format()
header_cell_format.set_rotation(90)
header_cell_format.set_align('center')
header_cell_format.set_align('vcenter')
然后...
# create list of dicts for header names
# (columns property accepts {'header': value} as header name)
col_names = [{'header': col_name} for col_name in df.columns]
# add table with coordinates: first row, first col, last row, last col;
# header names or formating can be inserted into dict
worksheet.add_table(0, 0, df.shape[0], df.shape[1], {
'columns': col_names,
# 'style' = option Format as table value and is case sensitive
# (look at the exact name into Excel)
'style': 'Table Style Medium 10'
})
或者可以使用worksheet.add_table('A1:D{}'.format(shape[0]), {...})
,但是对于具有更多列或起始位置偏移的df,必须计算AA,AB,...组合(而不是“ D”)
最后,下面的循环重写标头并应用header_cell_format。我们已经在worksheet.add_table(...)
中创建了它,因此它看起来很多余,但这是使用Excel的 AutoFit 选项的一种方法-如果没有此选项,所有标题单元格都将具有默认宽度(即单元格高度) (因为旋转了90度),所以不是整个文本都是可见的,或者不是必须应用set_shrink()……然后文本将不可读:)。
(在Office 365中测试)
# skip the loop completly if AutoFit for header is not needed
for i, col in enumerate(col_names):
# apply header_cell_format to cell on [row:0, column:i] and write text value from col_names in
worksheet.write(0, i, col['header'], header_cell_format)
# save writer object and created Excel file with data from DataFrame
writer.save()
答案 2 :(得分:0)
如果要将表格格式应用于使用XlsxWriter
输出到excel的数据框,请使用https://xlsxwriter.readthedocs.io/example_pandas_table.html上的文档
根据评论建议。
以下是我最初不太优雅的解决方案format_tbl
:
import pandas as pd
def format_tbl(writer, sheet_name, df):
outcols = df.columns
if len(outcols) > 25:
raise ValueError('table width out of range for current logic')
tbl_hdr = [{'header':c} for c in outcols]
bottom_num = len(df)+1
right_letter = chr(65-1+len(outcols))
tbl_corner = right_letter + str(bottom_num)
worksheet = writer.sheets[sheet_name]
worksheet.add_table('A1:' + tbl_corner, {'columns':tbl_hdr})
df = pd.DataFrame({
'city': ['New York', 'London', 'Prague'],
'population': [19.5, 7.4, 1.3],
'date_of_birth': ['1625', '43', 'early 8th century'],
'status_of_magnetism': ['nice to visit', 'nice to visit', 'definetely MUST visit']
})
fn_out='blah.xlsx'
with pd.ExcelWriter(fn_out, mode='w', engine='xlsxwriter') as writer:
sheet_name='xxx'
df.to_excel(writer, sheet_name=sheet_name, index=False)
format_tbl(writer, sheet_name, df)