问题
I am writing a Python script and stuck on one of the early steps. I am opening an existing sheet and want to add two columns so I have used this:
#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")
On line 12 I get an error:
name 'sheet1' is not defined
How do I define sheet 1 within the sheet that I have already opened?
回答1:
sheet1
is never declared. Try changing it to
#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: You could also use Pandas to read and write to 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')
回答2:
I guess you need to have something like
sheet1 = book.sheet_by_index(0)
; because now sheet1
is not defined.
Also, document is opened using xlrd
which is reader, and you need to write there values - so document should be opened also using xlwt
.
来源:https://stackoverflow.com/questions/53318383/how-to-get-python-script-to-write-to-existing-sheet