Как заставить скрипт Python писать на существующий лист - PullRequest
0 голосов
/ 15 ноября 2018

Я пишу скрипт на Python и застрял на одном из первых шагов. Я открываю существующий лист и хочу добавить два столбца, поэтому я использовал это:

#import the writer
import xlwt
#import the reader
import xlrd
#open the sussex results spreadsheet
book = xlrd.open_workbook('sussex.xlsx')
#open the first sheet
first_sheet = book.sheet_by_index(0)
#print the values in the second column of the first sheet
print first_sheet.col_values(1)
#in cell 0,0 (first cell of the first row) write "NIF"
sheet1.write(0, 6, "NIF")
#in cell 0,0 (first cell of the first row) write "Points scored"
sheet1.write(0, 6, "Points scored")

В строке 12 я получаю сообщение об ошибке:

name 'sheet1' is not defined

Как определить лист 1 на уже открытом листе?

Ответы [ 2 ]

0 голосов
/ 15 ноября 2018

sheet1 никогда не объявляется. Попробуйте изменить его на

#import the writer
import xlwt
#import the reader
import xlrd
#open the sussex results spreadsheet
book = xlrd.open_workbook('sussex.xlsx')
#open the first sheet
first_sheet = book.sheet_by_index(0)
#print the values in the second column of the first sheet
print first_sheet.col_values(1)
#in cell 0,0 (first cell of the first row) write "NIF"
first_sheet.write(0, 6, "NIF")
#in cell 0,0 (first cell of the first row) write "Points scored"
first_sheet.write(0, 6, "Points scored")

edit: Вы также можете использовать Панды для чтения и записи в Excel:

import pandas as pd
import numpy as np
#open the sussex results spreadsheet, first sheet is used automatically
df = pd.read_excel('sussex.xlsx')

#print the values in the second column of the first sheet
print(df.iloc[:,1])

#Create column 'NIF'
df['NIF'] = np.nan #I don't know what you want to do with this column, so I filled it with NaN's
#in cell 0,7 (first cell of the first row) write "Points scored"
df['Points scored'] = np.nan #I don't know what you want to do with this column, so I filled it with NaN's
<.... Do whatever calculations you want with NIF and Points scored ...> 
# Write output
df.to_excel('sussex.xlsx')
0 голосов
/ 15 ноября 2018

Полагаю, вам нужно что-то вроде sheet1 = book.sheet_by_index(0);потому что сейчас sheet1 не определено.Кроме того, документ открывается с помощью xlrd, который является читателем, и вам нужно записать туда значения - поэтому документ должен быть открыт также с помощью xlwt.

...