append rows in Excel using XLWT in Python

假如想象 提交于 2019-12-13 05:19:08

问题


How to find total number of rows using XLWT or XLRD in Python? I have an excel file(accounts.xls) and would like to append rows in it.

I am getting an error here - AttributeError: 'Sheet' object has no attribute 'write'

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'

回答1:


Here is the solution of the above question

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'



回答2:


Python Program to add Values to the last data row an Excel sheet.

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


来源:https://stackoverflow.com/questions/25144175/append-rows-in-excel-using-xlwt-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!