Easy way to populate an Excel file using Python

Say I have an excel file called test.xlsx , which is a book with three sheets, where sheet1 is called hello1 , sheet2 two is called hello2 , and sheet3 is called bye .

Now I would like to read the file and then overwrite the same file, but ONLY change the values ​​in the (column B, line 11) sheet named hello2 and (column D, line 14) the sheet named bye. The values ​​I want to give are the "test" (string) and 135, respectively (that is, the write test in sheets hello2 and 14 in the sheet).

You might be wondering why I am asking such a strange question, but basically I want to get some of the following skills / knowledge:

  • To be able to read a book and then a specific sheet of excel file using python
  • To be able to write to an excel sheet at a given position using python

Note: for reference, I can use any version of python on the redhat server, the excel file was generated with my mac, saved as xlsx format using excel for mac 2011. version 14.0.1, and then I copied the excel file to the redhat server.

+4
source share
1 answer

It doesn't seem like what you are doing depends on the values ​​already in the cells, so you don't need to use xlrd at all, except to open the book. The way xlrd , xlwt and xlutils is that you use xlrd to read a book, and then use xlutils to make a writable copy. So, a quick layout of your code will look like this:

 import xlrd, xlwt from xlutils.copy import copy rb = xlrd.open_workbook("Path/To/Doc", formatting_info=True) #Make Readable Copy wb = copy(rb) #Make Writeable Copy ws1 = wb.get_sheet(1) #Get sheet 1 in writeable copy ws1.write(1, 11, 'test') #Write 'test' to cell (1, 11) ws2 = wb.get_sheet(2) #Get sheet 2 in writeable copy ws2.write(3, 14, '135') #Write '135' to cell (3, 14) wb.save("New/File/Path") #Save the newly written copy. Enter the same as the old path to write over 
+6
source

Source: https://habr.com/ru/post/1498768/


All Articles