Store cell value of first few characters - python

I am trying to change the name of a sheet according to the value of a cell.
here is the code I am using.
from openpyxl import load_workbook
wb = load_workbook('file_name.xlsx')
ws = wb['Sheet 1']
sheet_name = ws['B2']
ws.title = f'Marketing {sheet_name}'
This code works, but
my problem is I only need to extract the first 3 characters from the cell ws['B2'].
How can I do that.

Use slicing:
sheet_name = ws['B2'].value[:3]

You can use the characters in the string.
Edit the parameters to get the desired result.
from openpyxl import load_workbook
wb = load_workbook('file_name.xlsx')
ws = wb['Sheet 1']
sheet_name = ws['B2'].value
ws.title = f'Marketing {sheet_name[0:3]}' # First character to third
Start reading the tabs by number so you don't have to change the tab name in the future.
Final code:
from openpyxl import load_workbook
wb = load_workbook('file_name.xlsx')
ws = wb.worksheets[0] # First tab
sheet_name = ws['B2'].value
ws.title = f'Marketing {sheet_name[0:3]}' # First character to third

Related

How to create autonumbering with Python in Openpyxl

I am trying to create an automatic numbering system with leading zeros in Python and openpyxl.
What is the best way to define the columns?
I would like to name them first and then say for each column what needs to be done.
Go to column 1 and put a numbering in it from 00001 to 00500.
Go to column 2 and put a numbering in there from 00501 to 01000.
...
In my opinion if I have these I can make any variants I want.
from openpyxl import Workbook, load_workbook
wb = Workbook()
ws = wb.active
ws.title = "Numbers"
ws.append(['N1','N2'])
#create Leading zero's
#zero_filled_number = number_str.zfill(5)
#print(zero_filled_number)
# Here I get stuck
for i in ws.append_columns(0)
i = range (1,500,1) number_str.zfill(5)
#ws.append_columns(1)
#for N2 in range (501,1000,1) number_str.zfill(5)
wb.save('Auto_numbers.xlsx')
from openpyxl import Workbook
import openpyxl
wb = Workbook()
sheet = wb.active
test_file = openpyxl.load_workbook('test.xlsx')
sheet = test_file.active
sheet['A1'] = 'ID'
counter = sheet.max_row
while counter < 10:
for row in sheet.rows:
counter += 1
sheet[f'A{counter}'] = f'N{counter}'
sheet.append([f'N{counter}'])
test_file.save('test.xlsx')

How to get only the output of a formula with excel openpyxl python

My code is:
import openpyxl
wb = openpyxl.load_workbook('C:\\xampp\\htdocs\\dad_app\\template\\template.xlsm')
sheet = wb.get_active_sheet()
sheet = wb.active
sheet['A1:AP701'] = sheet['A1:AP701'].internal_value
But it saves the formula too.
How do I remove the formula and only get the output?
You can pass data_only=True as a parameter in load_workbook. It will return the value stored the last time Excel read the sheet.
Documentation: Here
wb = openpyxl.load_workbook('C:\\xampp\\htdocs\\dad_app\\template\\template.xlsm', data_only=True)

Replacing row names in excel using python

I want to replace the names of the rows in my excel sheet. Whatever the row names may be, I have to replace them with:
Street
City
State
Zip
I am able to read the row names. Can anybody help me with replacing the names I read. Here is my piece of code. Thanks
import xlrd
workbook = xlrd.open_workbook('Path to Excel File')
sheet = workbook.sheet_by_index(0)
print(sheet)
for value in sheet.row_values(0):
print(value)
from openpyxl import load_workbook
wb = load_workbook('filename.xlsx')
ws = wb['sheetname']
ws.cell(row=1,column=1).value = 'Street'
ws.cell(row=1,column=2).value = 'City'
ws.cell(row=1,column=3).value = 'State'
ws.cell(row=1,column=4).value = 'Zip'
wb.save('filename.xlsx')

Fill cells with colors using openpyxl?

I am currently using openpyxl v2.2.2 for Python 2.7 and i wanted to set colors to cells. I have used the following imports
import openpyxl,
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles import colors
from openpyxl.cell import Cell
and the following is the code I tried using:
wb = openpyxl.Workbook()
ws = wb.active
redFill = PatternFill(start_color='FFFF0000',
end_color='FFFF0000',
fill_type='solid')
ws['A1'].style = redFill
but I get the following error:
Traceback (most recent call last)
self.font = value.font.copy()
AttributeError: 'PatternFill' object has no attribute 'font'
Any idea on how to set cell A1 (or any other cells) with colors using openpyxl?
I believe the issue is that you're trying to assign a fill object to a style.
ws['A1'].fill = redFill should work fine.
The API for styles changed once again. What worked for me was
my_red = openpyxl.styles.colors.Color(rgb='00FF0000')
my_fill = openpyxl.styles.fills.PatternFill(patternType='solid', fgColor=my_red)
cell.fill = my_fill
Color is an alpha RGB hex color. You can pass it in as 'rrggbb' with a default alpha of 00 or specify the alpha with 'aarrggbb'. A bunch of colors are defined as constants in openpyxl.styles.colors if you need to grab one quickly.
This worked for me. They changed things and most of the help you see on the internet is for older versions of the openpyxl library from what I am seeing.
# Change background color
xls_cell.style = Style(fill=PatternFill(patternType='solid',
fill_type='solid',
fgColor=Color('C4C4C4')))
in python 3.x
wb = openpyxl.Workbook()
ws = wb.active
redFill = PatternFill(start_color='FFFF0000',
end_color='FFFF0000',
fill_type='solid')
ws['A1'].fill = redFill
that working but i dont know in python 2.x i hope working
just put ws['A1'].fill=redFill
from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill
_file_name = "Test.xlsx"
_sheet_name = "Test_Sheet"
def new_workbook(_file_name, _sheet_name):
wb = Workbook() # Workbook Object
ws = wb.active # Gets the active worksheet
ws.title = _sheet_name # Name the active worksheet
# Writing the header columns
ws['A1'] = 'Name'
ws['B1'] = 'Class'
ws['C1'] = 'Section'
ws['D1'] = 'Marks'
ws['E1'] = 'Age'
col_range = ws.max_column # get max columns in the worksheet
# formatting the header columns, filling red color
for col in range(1, col_range + 1):
cell_header = ws.cell(1, col)
cell_header.fill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type="solid") #used hex code for red color
wb.save(_file_name) # save the workbook
wb.close() # close the workbook
if __name__ == '__main__':
new_workbook(_file_name, _sheet_name)
Result -
What I would do for Excel is this:
from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill
wb = load_workbook("test.xlsx")
ws = wb.active
ws["A1"].fill = PatternFill("solid", start_color="FFA500")
You can replace "A1" with another cell and start_color has to be a hex color.
To fill a range of rows/columns, do this
for cell in ws['A1:A100']:
cell[0].fill = redFill
To fill all rows of a column
for cell in ws['A1:{}'.format(ws.max_row)]:
cell[0].fill = redFill
Use a nested for loop to fill a two dimensional range.
Python 3.9
import openpyxl as op
fill_gen = op.styles.PatternFill(fill_type='solid',
start_color='FFFFFF',
end_color='FFFFFF')
for row in ws["A1:BB50"]:
for cell in row:
cell.fill = fill_gen

Writing multi-line strings into cells using openpyxl

I'm trying to write data into a cell, which has multiple line breaks (I believe \n), the resulting .xlsx has line breaks removed.
Is there a way to keep these line breaks?
The API for styles changed for openpyxl >= 2. The following code demonstrates the modern API.
from openpyxl import Workbook
from openpyxl.styles import Alignment
wb = Workbook()
ws = wb.active # wb.active returns a Worksheet object
ws['A1'] = "Line 1\nLine 2\nLine 3"
ws['A1'].alignment = Alignment(wrapText=True)
wb.save("wrap.xlsx")
Disclaimer: This won't work in recent versions of Openpyxl. See other answers.
In openpyxl you can set the wrap_text alignment property to wrap multi-line strings:
from openpyxl import Workbook
workbook = Workbook()
worksheet = workbook.worksheets[0]
worksheet.title = "Sheet1"
worksheet.cell('A1').style.alignment.wrap_text = True
worksheet.cell('A1').value = "Line 1\nLine 2\nLine 3"
workbook.save('wrap_text1.xlsx')
This is also possible with the XlsxWriter module.
Here is a small working example:
from xlsxwriter.workbook import Workbook
# Create an new Excel file and add a worksheet.
workbook = Workbook('wrap_text2.xlsx')
worksheet = workbook.add_worksheet()
# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)
# Add a cell format with text wrap on.
cell_format = workbook.add_format({'text_wrap': True})
# Write a wrapped string to a cell.
worksheet.write('A1', "Line 1\nLine 2\nLine 3", cell_format)
workbook.close()
Just an additional option, you can use text blocking """ my cell info here """ along with the text wrap Boolean in alignment and get the desired result as well.
from openpyxl import Workbook
from openpyxl.styles import Alignment
wb= Workbook()
sheet= wb.active
sheet.title = "Sheet1"
sheet['A1'] = """Line 1
Line 2
Line 3"""
sheet['A1'].alignment = Alignment(wrapText=True)
wb.save('wrap_text1.xlsx')
Just in case anyone is looking for an example where we iterate over all cells to apply wrapping:
Small working example:
import pandas as pd
from openpyxl import Workbook
from openpyxl.styles import Alignment
from openpyxl.utils.dataframe import dataframe_to_rows
# create a toy dataframe. Our goal is to replace commas (',') with line breaks and have Excel rendering \n as line breaks.
df = pd.DataFrame(data=[["Mark", "Student,26 y.o"],
["Simon", "Student,31 y.o"]],
columns=['Name', 'Description'])
# replace comma "," with '\n' in all cells
df = df.applymap(lambda v: v.replace(',', '\n') if isinstance(v, str) else v)
# Create an empty openpyxl Workbook. We will populate it by iteratively adding the dataframe's rows.
wb = Workbook()
ws = wb.active # to get the actual Worksheet object
# dataframe_to_rows allows to iterate over a dataframe with an interface
# compatible with openpyxl. Each df row will be added to the worksheet.
for r in dataframe_to_rows(df3, index=True, header=True):
ws.append(r)
# iterate over each row and row's cells and apply text wrapping.
for row in ws:
for cell in row:
cell.alignment = Alignment(wrapText=True)
# export the workbook as an excel file.
wb.save("wrap.xlsx")

Categories