1

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: enter image description here

After I wrote data into the file: enter image description here

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?

2
  • I think you can take a look this: stackoverflow.com/questions/13437727/… Commented Jul 27, 2018 at 7:17
  • @LêTưThành - actually it is quite a nice link, but only one of the answers stackoverflow.com/a/29979532/5448626 answers to the question of the OP. However, that answer is from 2015 and the function get_sheet_by_name is depreciated by now. Commented Jul 27, 2018 at 8:15

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.