如何使Python脚本写入现有工作表

时间:2018-11-15 11:22:54

标签: python excel xlwt

我正在编写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 :(得分:1)

我想你需要像 sheet1 = book.sheet_by_index(0);因为现在sheet1尚未定义。 同样,使用阅读器xlrd打开文档,您需要在其中写入值-因此也应使用xlwt打开文档。

答案 1 :(得分:1)

从未声明

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