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?

dnisqa2 delta
  • 161
  • 1
  • 5
  • 9
  • I think you can take a look this: https://stackoverflow.com/questions/13437727/python-write-to-excel-spreadsheet – Lê Tư Thành Jul 27 '18 at 07:17
  • @LêTưThành - actually it is quite a nice link, but only one of the answers https://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. – Vityata Jul 27 '18 at 08:15

2 Answers2

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.

Vityata
  • 42,633
  • 8
  • 55
  • 100
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')
Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
hyperzy
  • 11
  • 1