如何在单个工作簿中使用openpyxl同时写入两张纸 [英] How to write two sheets in a single workbook at the same time using openpyxl

查看:784
本文介绍了如何在单个工作簿中使用openpyxl同时写入两张纸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建并编写一个有5个工作表的新的excel工作簿。我的代码的目的是读取数据库并根据某些标准将其拆分成不同的表格。



我在python 2.7中使用了以下的代码,使用openpyxl-1.1。 0

  from openpyxl.workbook import Workbook 
dest_filename ='D:\\Splitted.xlsx'

wb = Workbook()
ws1 = wb.worksheets [0]
ws1.title ='Criterion1'

ws2 = wb.worksheets [1]
ws2.title ='Criterion2'

##读取数据库,获得标准
如果标准== Criterion1:
ws1.cell('A1')。 ='A1'
ws1.cell('B1')value ='B1'
elif标准== Criterion2:
ws2.cell('A1')。value ='A2'
ws2.cell('B1')。value ='B2'

wb.save(filename = dest_filename)

我可以写单页,但是如果我尝试创建第二个工作表,我在代码
ws2 =得到一个错误,说索引超出范围 wb.workshe ets [1]



是否有任何解决方案可以在同一时间在单个工作簿中写入2个或更多工作表?

解决方案

您不应该通过索引尝试访问工作表。错误是因为第二个工作表尚未创建(每个工作簿都有自动创建的单个工作表)。

  ws1 = wb .active 
ws2 = wb.create_sheet()

应该解决你的问题。 >

I have to create and write a new excel workbook with about 5 worksheets. The purpose of my code is to read a database and split that into different sheets depending on certain criterion.

I have used the following code in python 2.7 using openpyxl-1.1.0

from openpyxl.workbook import Workbook
dest_filename = 'D:\\Splitted.xlsx'

wb = Workbook()
ws1 = wb.worksheets[0]
ws1.title = 'Criterion1'

ws2 = wb.worksheets[1]
ws2.title = 'Criterion2'

## Read Database, get criterion
if criterion == Criterion1:
    ws1.cell('A1').value = 'A1'
    ws1.cell('B1').value = 'B1'
elif criterion == Criterion2:
    ws2.cell('A1').value = 'A2'
    ws2.cell('B1').value = 'B2'

wb.save(filename = dest_filename)

I am able to write single sheet, but if I try to create 2nd worksheet, I am getting an error saying "Index out of range" at code ws2 = wb.worksheets[1]

Is there any solution to write 2 or more worksheets in a single workbook at the same time?

解决方案

You shouldn't try and access worksheets by index. The error is because the second worksheet hasn't been created (every workbook has a single worksheet created automatically).

ws1 = wb.active
ws2 = wb.create_sheet()

Should solve your problem.

这篇关于如何在单个工作簿中使用openpyxl同时写入两张纸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆