Write values to a particular cell in a sheet in pandas in python

前端 未结 3 1719
执念已碎
执念已碎 2020-12-23 18:24

I have an excel sheet, which already has some values in some cells.

For ex :-

        A      B      C      D
1      val1   val2          val3
2              


        
3条回答
  •  长情又很酷
    2020-12-23 18:53

    I was not able to do what was asked by me in the question by using pandas, but was able to solve it by using Openpyxl.

    I will write few code snippets which would help in achieving what was asked.

    import openpyxl
    
    srcfile = openpyxl.load_workbook('docname.xlsx',read_only=False, keep_vba= True)#to open the excel sheet and if it has macros
    
    sheetname = srcfile.get_sheet_by_name('sheetname')#get sheetname from the file
    sheetname['B2']= str('write something') #write something in B2 cell of the supplied sheet
    sheetname.cell(row=1,column=1).value = "something" #write to row 1,col 1 explicitly, this type of writing is useful to write something in loops
    
    srcfile.save('newfile.xlsm')#save it as a new file, the original file is untouched and here I am saving it as xlsm(m here denotes macros).
    

    So Openpyxl writes to a purticular cell, without touching the other sheets,cells etc. It basically writes to a new file respecting the properties of the original file

提交回复
热议问题