使用openpyxl对XLSX工作簿中的选项卡进行排序

时间:2019-01-15 19:33:35

标签: python openpyxl

我不确定是否应该创建一个新问题,因为接受的答案无效。请指教。我是否只是回答相同的问题作为答案?这是相同的问题:How can I sort excel sheets/tabs in workbook using openpyxl。我不确定它是否由于用户问题(通常是)或openpyxl的旧/新版本而无法使用。

这是我的代码:

from openpyxl import Workbook
wb = Workbook()

ws1 = wb.create_sheet("B")
ws2 = wb.create_sheet("A")
ws3 = wb.create_sheet("C")
ws4 = wb.create_sheet("D")

wb._sheets = sorted(wb._sheets) #Error comes up at this line

wb.save('test_tabs.xlsx')

我收到以下错误:

TypeError: '<' not supported between instances of 'Worksheet' and 'Worksheet'

因此,我尝试手动对工作表列表进行排序:

>>> type(wb._sheets)
<class 'list'>

>>> wb._sheets
[<Worksheet "Sheet">, <Worksheet "B">, <Worksheet "A">, <Worksheet "C">, <Worksheet "D">]

>>> wb._sheets = [<Worksheet "A">, <Worksheet "B">, <Worksheet "C">, <Worksheet "D">, <Worksheet "Sheet">]
File "<stdin>", line 1

# Manual sort of sheets
wb._sheets = [<Worksheet "A">, <Worksheet "B">, <Worksheet "C">, <Worksheet "D">, <Worksheet "Sheet">]
              ^
SyntaxError: invalid syntax

我注意到列表项没有被'"包围,所以我想知道sort是否因此而失败。

而且,为了踢球,我尝试将'添加到列表项:

wb._sheets = ['<Worksheet "A">', '<Worksheet "B">', '<Worksheet "C">', '<Worksheet "D">', '<Worksheet "Sheet">']

>>> wb._sheets
['<Worksheet "A">', '<Worksheet "B">', '<Worksheet "C">', '<Worksheet  "D">', '<Worksheet "Sheet">']

>>> wb.save('test_tabs2.xlsx')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
....
AttributeError: 'str' object has no attribute 'sheet_state'

>>> openpyxl.__version__
'2.4.1'

1 个答案:

答案 0 :(得分:2)

以下解决方案(在ws.titlefrom openpyxl import Workbook wb = Workbook() ws1 = wb.create_sheet("B") ws2 = wb.create_sheet("A") ws3 = wb.create_sheet("C") ws4 = wb.create_sheet("D") wb._sheets.sort(key=lambda ws: ws.title) wb.save('test_tabs.xlsx') )对我有用:

select p.date, sum(p.pageviews) as "total_pageviews", sum(p.sessions) as "total_sessions",l.location_id, p.brand_key
FROM public.local_site_sessions p, public.location_map l
where l.affiliate_id = p.affiliate_id
group by p.date, p.brand_key, l.location_id 

union

select g.date, g.sessions , g.pages_per_session ,g.location_id, brand_key
FROM public.ga_lead g

结果:

enter image description here