Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

For ex :-

        A      B      C      D
1      val1   val2          val3
2             valx   valy        

I want pandas to write to specific cells without touching any other cells,sheet etc

This is the code i tried.

import pandas as pd
from openpyxl import load_workbook

df2 = pd.DataFrame({'Data': [13, 24, 35, 46]})
book = load_workbook('b.xlsx')
writer = pd.ExcelWriter('b.xlsx', engine='openpyxl')

df2.to_excel(writer, "Sheet1", startcol=7,startrow=6)

writer.save()

However this code deletes the older cell values.

I have reffered to :- How to write to an existing excel file without overwriting data (using pandas)? but this solution does not work.

like image 800
penta Avatar asked Oct 01 '16 10:10

penta


People also ask

How do you write to a cell in Python?

There are two basic ways to write to a cell: using a key of a worksheet such as A1 or D3, or using a row and column notation with the cell method. In the example, we write two values to two cells. Here, we assing a numerical value to the A1 cell. In this line, we write to cell B2 with the row and column notation.

How do you assign a value to a cell in a data frame?

You can set cell value of pandas dataframe using df.at[row_label, column_label] = 'Cell Value'. It is the fastest method to set the value of the cell of the pandas dataframe. Dataframe at property of the dataframe allows you to access the single value of the row/column pair using the row and column labels.


2 Answers

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

# to open the excel sheet and if it has macros
srcfile = openpyxl.load_workbook('docname.xlsx', read_only=False, keep_vba=True)

# get sheetname from the file
sheetname = srcfile.get_sheet_by_name('sheetname')
# write something in B2 cell of the supplied sheet
sheetname['B2'] = str('write something')
# write to row 1,col 1 explicitly, this type of writing is useful to
# write something in loops
sheetname.cell(row=1, column=1).value = 'something'

# save it as a new file, the original file is untouched and here I am saving
# it as xlsm(m here denotes macros).
srcfile.save('newfile.xlsm')

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.

like image 39
penta Avatar answered Oct 12 '22 14:10

penta


UPDATE2: appending data to existing Excel sheet, preserving other (old) sheets:

import pandas as pd
from openpyxl import load_workbook

fn = r'C:\Temp\.data\doc.xlsx'

df = pd.read_excel(fn, header=None)
df2 = pd.DataFrame({'Data': [13, 24, 35, 46]})

writer = pd.ExcelWriter(fn, engine='openpyxl')
book = load_workbook(fn)
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

df.to_excel(writer, sheet_name='Sheet1', header=None, index=False)
df2.to_excel(writer, sheet_name='Sheet1', header=None, index=False,
             startcol=7,startrow=6)

writer.save()

UPDATE: your Excel file doesn't have a header, so you should process it accordingly:

In [57]: df = pd.read_excel(fn, header=None)

In [58]: df
Out[58]:
     0    1
0  abc  def
1  ghi  lmn

In [59]: df2
Out[59]:
   Data
0    13
1    24
2    35
3    46

In [60]: writer = pd.ExcelWriter(fn)

In [61]: df.to_excel(writer, header=None, index=False)

In [62]: df2.to_excel(writer, startcol=7,startrow=6, header=None, index=False)

In [63]: writer.save()

enter image description here

OLD answer:

You can use the following trick:

first read the existing contents of the excel file into a new DF:

In [17]: fn = r'C:\Temp\b.xlsx'

In [18]: df = pd.read_excel(fn)

In [19]: df
Out[19]:
       A      B     C      D
0   val1    NaN  val3   val4
1  val11  val22   NaN  val33

now we can write it back and append a new DF2:

In [20]: writer = pd.ExcelWriter(fn)

In [21]: df.to_excel(writer, index=False)

In [22]: df2.to_excel(writer, startcol=7,startrow=6, header=None)

In [23]: writer.save()

enter image description here

like image 53
MaxU - stop WAR against UA Avatar answered Oct 12 '22 15:10

MaxU - stop WAR against UA