我第一次使用openpyxl。我必须阅读excel文件,然后在操作之后,将结果填充在三个不同的Excel工作表上 - > sheet_T,sheet_D和sheet_U。我使用openpyxl创建了三张表,如下所示 -
A B C D group scores
1 1 0 0 0 A 0.73130714
2 0 1 0 0 B 0.60615966
3 0 0 1 0 C 0.74046980
4 0 0 0 1 D 0.13636377
5 1 0 0 0 A 0.33951820
6 0 1 0 0 B 0.95789481
7 0 0 1 0 C 0.26756629
8 0 0 0 1 D 0.71264870
9 1 0 0 0 A 0.87482811
10 0 1 0 0 B 0.69434779
11 0 0 1 0 C 0.92821292
12 0 0 0 1 D 0.70466255
13 1 0 0 0 A 0.30458528
14 0 1 0 0 B 0.90092407
15 0 0 1 0 C 0.77997403
16 0 0 0 1 D 0.05661558
我用xlwt来做,但是有256列的约束。因此,我使用openpyxl。下面的代码是使用xlwt -
编写的sheet_T = filename2.create_sheet(0)
sheet_T.title = "Target First"
sheet_D = filename2.create_sheet(1)
sheet_D.title = "Distractor First"
sheet_U = filename2.create_sheet(2)
sheet_U.title = "Unclassified"
如何使用openpyxl编写相同的内容?我读到的所有文档都是如何在特定单元格而不是表格上书写。
非常感谢您的帮助!
答案 0 :(得分:0)
您需要创建另一张表:
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter
wb = Workbook()
ws0 = wb.worksheets[0]
ws0.title = 'My Sheet 1'
ws1 = wb.create_sheet()
ws1.title = 'My Sheet 2'
ws2 = wb.create_sheet()
ws2.title = 'My Sheet 3'
现在你可以写到不同的表格:
cell_ws0_a1 = ws0.cell('A1')
cell_ws0_a1.value = 'Wrote to cell in 1st sheet.'
cell_ws1_a1 = ws1.cell('A1')
cell_ws1_a1.value = 'Wrote to cell in 2nd sheet.'
cell_ws2_a1 = ws2.cell('A1')
cell_ws2_a1.value = 'Wrote to cell in 3rd sheet.'
writer = ExcelWriter(workbook=wb)
writer.save('example.xlsx')
默认情况下,工作簿中只有一个工作表。 wb.create_sheet()
创建第二张表。