【问题标题】:excel file with the ability to filter columns具有过滤列能力的excel文件
【发布时间】:2015-12-02 20:12:36
【问题描述】:

我需要创建带有可以过滤的列的 excel。

更喜欢使用 openpyxl,因为我已经使用 StyleFrame 来设置 excel 的样式。

example

【问题讨论】:

  • openpyxl 支持过滤器。
  • 类 openpyxl.worksheet.filters.AutoFilter link
  • 非常感谢它的工作原理!

标签: python excel openpyxl styleframe


【解决方案1】:

此代码使用 xlwt。 它写入行和列。

import xlwt

def writelineSimple(shet,line, lstLine):
    col=0
    for elem in lstLine:
        shet.write(line, col, elem)
        col=col+1

def writecolum(shet,line,col, lstLine):
    for elem in lstLine:
        shet.write(line, col, elem)
        line=line+1

def writeline(shet,line,col, lstLine):
    for elem in lstLine:
        shet.write(line, col, elem)
        col=col+1


book = xlwt.Workbook(encoding="utf-8")
sheet1 = book.add_sheet("Sheet 1")

writelineSimple(sheet1,0,["col1","col2","col3","col4","col5"])
writelineSimple(sheet1,1,["writelineSimple1","writelineSimple2"])
writeline(sheet1,3,3,["writeline1","writeline2","writeline3"])
writecolum(sheet1,5,5,["writecolum1","writecolum2","writecolum3"])


book.save("myfirstgeneratedexcel.xls")

myfirstgeneratedexcel.xls

col1    col2    col3    col4    col5    
writelineSimple1    writelineSimple2                

            writeline1  writeline2  writeline3

                    writecolum1
                    writecolum2
                    writecolum3

【讨论】:

  • xlwt 不支持 XLSX 文件。
【解决方案2】:

这是使用 StyleFrame 的解决方案,我必须使用索引为 0 的“row_to_add_filters”来向列添加过滤器......

from StyleFrame import StyleFrame, colors

excel_writer = StyleFrame.ExcelWriter('example.xlsx')
sf = StyleFrame({'a': [1, 2, 3], 'b': [1, 1, 1], 'c': [2, 3, 4]})
sf.apply_column_style(cols_to_style=['a', 'c'], protection=True, style_header=True)
sf.apply_style_by_indexes(indexes_to_style=2, cols_to_style='b', bg_color=colors.yellow, protection=True)
sf.to_excel(excel_writer=excel_writer, row_to_add_filters=0, columns_and_rows_to_freeze='B2', allow_protection=True)
excel_writer.save()

【讨论】:

    猜你喜欢
    • 2014-08-19
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多