如何让 Python 脚本写入现有 sheet

How to get Python script to write to existing sheet

我正在编写一个 Python 脚本并停留在早期步骤之一。我正在打开一个现有的 sheet 并想添加两列,所以我使用了这个:

#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

如何在已经打开的sheet中定义sheet1?

我想你需要有类似的东西 sheet1 = book.sheet_by_index(0);因为现在 sheet1 没有定义。 此外,文档使用 xlrd 打开,即 reader,您需要在其中写入值 - 因此文档也应使用 xlwt.

打开

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")

编辑:您还可以使用 Pandas 读取和写入 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')