[英]How to get Python script to write to existing sheet
I am writing a Python script and stuck on one of the early steps. 我正在编写Python脚本,并停留在早期步骤之一。 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: 在第12行,我得到一个错误:
name 'sheet1' is not defined
How do I define sheet 1 within the sheet that I have already opened? 如何在已打开的工作表中定义工作表1?
I guess you need to have something like sheet1 = book.sheet_by_index(0)
; 我猜你需要像sheet1 = book.sheet_by_index(0)
这样的东西; because now sheet1
is not defined. 因为现在未定义sheet1
。 Also, document is opened using xlrd
which is reader, and you need to write there values - so document should be opened also using xlwt
. 另外,使用阅读器xlrd
打开文档,您需要在其中写入值-因此也应使用xlwt
打开文档。
sheet1
is never declared. sheet1
从未声明过。 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: 编辑:您也可以使用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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.