如何在Python中使用XLWT或XLRD查找总行数?我有一个excel文件(accounts.xls),并希望在其中追加行。
我在这里收到错误 - AttributeError:' Sheet'对象没有属性'写'
from xlrd import open_workbook
from xlwt import Workbook
def saveWorkSpace(fields,r):
wb = open_workbook('accounts.xls')
ws = wb.sheet_by_index(0)
r = ws.nrows
r += 1
wb = Workbook()
ws.write(r,0,fields['name'])
ws.write(r,1,fields['phone'])
ws.write(r,2,fields['email'])
wb.save('accounts.xls')
print 'Wrote accounts.xls'
答案 0 :(得分:5)
以下是上述问题的解决方案
import xlrd
import xlwt
from xlutils.copy import copy
def saveWorkSpace(fields):
rb = xlrd.open_workbook('accounts.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0)
r = r_sheet.nrows
wb = copy(rb)
sheet = wb.get_sheet(0)
sheet.write(r,0,fields['name'])
sheet.write(r,1,fields['phone'])
sheet.write(r,2,fields['email'])
wb.save('accounts.xls')
print 'Wrote accounts.xls'
答案 1 :(得分:0)
from xlwt import Workbook
from xlrd import open_workbook
import openpyxl
# Function to get the last RowCount in the Excel sheet , change the index of the sheet accordingly to get desired sheet.
def getDataColumn():
#define the variables
rowCount=0
columnNumber=0
wb = open_workbook('C:\\Temp\\exp\\data.xlsx')
ws = wb.sheet_by_index(0)
rowCount = ws.nrows
rowCount+=1
columnNumber=1
print(rowCount)
writedata(rowCount,columnNumber)
#Data to specified cells.
def writedata(rowNumber,columnNumber):
book = openpyxl.load_workbook('C:\\Temp\\exp\\data.xlsx')
sheet = book.get_sheet_by_name('Sheet1')
sheet.cell(row=rowNumber, column=columnNumber).value = 'Appended Data'
book.save('C:\\Temp\\exp\\data.xlsx')
print('saved')
getDataColumn()
exit()