简体   繁体   中英

How to write a data into an exist sheet of excel file by Python?

I'm looking for a way to write some data into an excel file. Then I found xlwt seems can reach my requirement, but I only find the way to add a new sheet. for example:

sheet = workbook.add_sheet('test222')

If I hope to enter a value into an exist sheet "test 111", does someone know how to do that?

My sample code:

import xlwt

def write_report():
    f_value = "500"
    workbook = xlwt.Workbook('D:\\Test.xls')
    sheet = workbook.add_sheet('test222')
    sheet.write(5, 3, f_value)

    workbook.save('D:\\Test.xls')

Thanks a lot.





[Update on 7/31/2018]
After I used the method of import openpyxl, I met a weird issue. Some borders were disappeared after I write data into the file.
Original: 在此处输入图片说明

After I wrote data into the file: 在此处输入图片说明

The border of some fields which have been merged were cleared. (item A, item B, Category 01 and Category 02) Is it the known issue on openpyxl?

This is minmal example:

import openpyxl

wbkName = 'New.xlsx'
wbk = openpyxl.load_workbook(wbkName)
wks = wbk['test1']
someValue = 1337
wks.cell(row=10, column=1).value = someValue
wbk.save(wbkName)
wbk.close

The saving with the explicit name of the workbook seems to be quite important - wbk.save(wbkName) , because only wbk.save does not do the job completely, but does not throw an error.

You can use xltpl for this - A python module to generate xls/x files from a xls/x template.

Use your excel file as the template.
Put variables in the cells, such as : {{f_value}}, {%xv someValue%}

from xltpl.writer import BookWriter
writer = BookWriter('template.xls')
payload = {"f_value": "500", "someValue": 1337}
payloads = [payload]
writer.render_book(payloads)
writer.save('result.xls')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM