Write values to cells in Excel dynamically in Python - python

I am using the openpyxl method to write values in Python to Excel. I have around 30 integer values in python which I want to dynamically write to specific Excel cells.
For example, value1-value5 should be written to B1-B5, when this is complete, we should move to the next column and write value6-value10 in cells C1-C5.
I am using the below code, but need help making it dynamic
#create workbook object
wb=openpyxl.load_workbook("report.xlsx")
type (wb)
#get sheet names
wb.get_sheet_names()
#create reference for sheet on which to write
worksheet= wb.get_sheet_by_name("Sheet1")
#use sheet reference and write the cell address
**worksheet["B1"]=value1** #this part needs to be automated
#save workbook
wb.save("report.xlsx")

If you want to create these reference strings dynamically this will help:
column, row = 66, 1
for v in values:
if row == 6:
row = 1
column += 1
worksheet['{}{}'.format(chr(column),row)] = value
row += 1
This will start with B1 and once it reaches B5 it will move to C1 and so on.
Doesn't work after column Z.

Related

Openpyxl: Code fails to write data from one Excel spreadsheet to another

I am trying to use Openpyxl to search for data in one Excel workbook, and write it to another (pre-existing) Excel workbook. The aim is something like this:
Search in Workbook1 for rows containing the word "Sales" (there being several such rows)
Copy the data from Column E of those rows (a numerical value), into a specific cell in Workbook2 (second worksheet, cell C3).
My code below appears to run without any errors, however, when I open Workbook 2, no data is being written in to it. Does anyone know why/can suggest a fix?
# importing openpyxl module
import openpyxl as xl
import sys
# opening the source excel file
filename ="C:\\Users\\hadam\\Documents\\Testing\\TB1.xlsx"
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]
# opening the destination excel file
filename1 = "C:\\Users\\hadam\\Documents\\Testing\\comp2.xlsx"
wb2 = xl.load_workbook(filename1)
ws2 = wb2.worksheets[1]
for sheet in wb1.worksheets:
for row in sheet.iter_rows():
for cell in row:
try:
if 'Sale' in cell.value:
# reading cell value from source excel file
c = ws1.cell(row=cell.row, column=4).value
# writing the read value to destination excel file
ws2.cell(row=2, column=2).value = c.value
except (AttributeError, TypeError):
continue
# saving the destination excel file
wb2.save(str(filename1))
sys.exit()
Other info:
Specifically, the text string I am searching for ('Sales') is in Column A of Workbook1. It is not an exact match, but e.g. a given cell contains "5301 Sales - Domestic - type4". Therefore I want to sum the numerical values in Column E which contain "Sales" in Column A, into a single cell in Workbook2.
I am mega new to Python/coding. However, my environment seems to be set up okay, e.g. I have already tested a code (copied from elsewhere in the Web) that can write all the data from one spreadsheet into another pre-existing spreadsheet). I am using Mu editor in Python 3 mode and openpyxl module.
The line
c = ws1.cell(row=cell.row, column=4).value
copies the value in Col 4 to the variable 'c'. 'column=4' is Column D in the spreadsheet, you want this to be 'column=5' to get the value from Column E. If Column D is empty c would have no value each time.
In your code c is equal to the value in that Column E which matches your search criteria, currently it would be overwritten on each iteration of the loop. To sum the values you must add each new value to the existing value of c for each iteration using '+='.
There is no need to update the 2nd book cell value for each loop, you only want the resulting sum writen so these steps can be completed once the sum has
been calculated at the completion of the loop.
See code below that modifies that part of your code;
initialize c
c = 0
change the line so c sums the value in Col E for each loop match
c += ws1.cell(row=cell.row, column=5).value
then place the cell value update and save to excel book at the same indentation as the loop so this is executed once the loop completes.
Note that c is a python integer it has no attribute called value it's just 'c'. Using 'c.value' would give a blank value. Also the cell C3 you want to write this value to is row/col 3
ws2.cell(row=3, column=3).value = c
Finally save the cell to the 2nd excel book
Modded code;
...
c = 0
for sheet in wb1.worksheets:
for row in sheet.iter_rows():
for cell in row:
try:
if 'Sale' in cell.value:
# reading cell value from source excel file
c += ws1.cell(row=cell.row, column=5).value
except (AttributeError, TypeError):
continue
# writing the read value to destination excel file
ws2.cell(row=3, column=3).value = c
# saving the destination excel file
wb2.save(str(filename1))
...

Lookup the id of an excel cell by checking if value exists using python

I'm trying to edit some information in an excel table using python. I have a list of registrations, pickup dates and delivery dates. I want to check if the registration exists in some of the cells of the excel document and then modify its corresponding pickup and delivery dates. I'm fairly new to python as a whole so this task, although at first seeming simple has proved to be quite challenging. How can I locate the specific table ID by checking if it holds a certain value?
Table for reference:
Alright so I solved the problem myself, posting this answer in case somebody else needs to do something similar.
I used the openpyxl library.
//Create a workbook reference an load it using the openpyxl load_workbook()
method by passing in the path to the excel workbook
workbook = openpyxl.load_workbook(workbook_path)
//Craete instance of a worksheet and pass the name of the worksheet you want to edit
current_worksheet = workbook['Sheet1']
//Get the number of rows so that we know how many registrations we need to edit
row_count = current_worksheet.max_row
//Loop through the registrations on the excel sheet, starting from 2 since 1 is the cell
containing "Car Registration"
for j in range(2, row_count):
//Use the worksheet instance and call the cell() method to point to a specific cell and
fetch the registration from that cell
registration_cell = current_worksheet.cell(row = j, column = 1)
current_registration_plate = registration_cell.value
//Compare the fetched registration with the registration we are trying to find. If so
create variables which point to two new cells using the same row where the id was found
(j), add the needed values into them using again .value. and break the loop
if (current_registration_plate == registration_plate):
pickup_cell = current_worksheet.cell(row = j, column = 2)
pickup_cell.value = pickup_value
dropoff_cell = current_worksheet.cell(row = j, column = 3)
dropoff_cell.value = dropoff_value
break
//Save changes to workbook after finishing the loop
workbook.save(workbook_path)

manipulating excel spreadsheets with python

I am new to Python especially when it comes to using it with Excel. I need to write code to search for the string “Mac”, “Asus”, “AlienWare”, “Sony”, or “Gigabit” within a longer string for each cell in column A. Depending on which of these strings it finds within the entire entry in column A’s cell, it should write one of these 5 strings to the corresponding row in column C’s cell. Else if it doesn’t find any of the five, it would write “Other” to the corresponding row in column C. For example, if Column A2’s cell contained the string “ProLiant Asus DL980 G7, the correct code would write “Asus” to column C2’s cell. It should do this for every single cell in column A, writing the appropriate string to the corresponding cell in column C. Every cell in column A will have one of the five strings Mac, Asus, AlienWare, Sony, or Gigabit within it. If it doesn’t contain one of those strings, I want the corresponding cell in column 3 to have the string “Other” written to it. So far, this is the code that I have (not much at all):
import openpyxl
wb = openpyxl.load_workbook(path)
sheet = wb.active
for i in range (sheet.max_row):
cell1 = sheet.cell (row = i, column = 1)
cell2 = sheet.cell (row = I, column = 3)
# missing code here
wb.save(path)
You haven't tried writing any code to solve the problem. You might want to first get openpyxl to write to the excel workbook and verify that is working - even if it's dummy data. This page looks helpful - here
Once that is working all you'd need is a simple function that takes in a string as an argument.
def get_column_c_value(string_from_column_a):
if "Lenovo" in string_from_column_a:
return "Lenovo"
else if "HP" in string_from_column_a:
return "HP"
# strings you need to check for here in the same format as above
else return "other"
Try out those and if you have any issues let me know where you're getting stuck.
I have not worked much with openpyxl, but it sounds like you are trying to do a simple string search.
You can access individual cells by using
cell1.internal_value
Then, your if/else statement would look something like
if "HP" in str(cell1.internal_value):
Data can be assigned directly to a cell so you could have
ws['C' + str(i)] = "HP"
You could do this for all of the data in your cells

Going down columns using xlrd

Let's say I have a cell (9,3). I want to get the values from (9,3) to (9,99). How do I go down the columns to get the values. I am trying to write the values into another excel file that starts from (13, 3) and ends at (13,99). How do I write a loop for that in xlrd?
def write_into_cols_rows(r, c):
for num in range (0,96):
c += 1
return (r,c)
worksheet.row(int) will return you the row, and to get the value of certain columns, you need to run row[int].value to get the value.
For more information, you can read this pdf file (Page 9 Introspecting a sheet).
import xlrd
workbook = xlrd.open_workbook(filename)
# This will get you the very first sheet in the workbook.
worksheet = workbook.sheet_by_name(workbook.sheet_names()[0])
for index in range(worksheet.nrows):
try:
row = worksheet.row(index)
row_value = [col.value for col in row]
# now row_value is a list contains all the column values
print row_value[3:99]
except:
pass
To write data to Excel file, you might want to check out xlwt package.
BTW, seems like you are doing something like reading from excel.. do some work... write to excel...
I would also recommend you take a look at numpy, scipy or R. When I usually do data munging, I use R and it saves me so much time.

Extracting values only from the value of excel row recived using xlrd -python

This problem is specific wrt using xlrd package in python
I got row of excel which is in form of list but each item is integer value;
type:value
this is not string. The row is save by;
import xlrd
book = xlrd.open_workbook('myfile.xls')
sh = book.sheet_by_index(0)
for rx in range(sh2.nrows):
row = sh.row(rx)
so row saved has value;
row=[text:u'R', text:u'xyz', text:u'Y', text:u'abc', text:u'lmn', empty:'']
This is a list of int. I want the values extracted -
R
xyz
Y
abc
lmn
''
There has to be some method to convert it, but not sure which and how.
Now, I know I can get value just by;
cell_value = sh.cell_value(rowx=rx, colx=1)
but my program requires to collect rows first and then extract values from save row.
Thanks.
The row is a sequence of Cell instances, which have the attribute value.
for cell in row:
cell_value = cell.value
# etc
I am not sure why you want to do it this way - the reference to collecting rows first seems odd to me, given that you can get the rows directly from the worksheet.

Categories

Resources