You are on page 1of 41
A Guide to Excel Spreadsheets in Python With openpyxl by Pedro Pregucio @82 Comments * (insmedi) MarkasCompleted Table of Contents + Before You Begin © Practe © Learning Some Basic Excel Terminology © Getting Started with openpyal + Reading Excel Sareadsheets With opeapyal © Dataset for This Tutorial, © ASimple Aopraach to Reading an Excel Spreadsheet cases © Adding Pretty Charts © Convert Python Classes to Excel Spreadsheet ‘© Bonus: Working With Pandas + Conclusion aT tn) Become a Python Expert » rN Be Python Expert (TTD) This tutorial has a related video course created by the Real Python team. Watch ttogether with the ‘written tutorial to deepen your understanding: Editing Excel Spreadsheets in Python With openpyxl Excel spreadsheets are one of those things you might have to deal with at some point. Either it's because your boss loves them or because marketing needs them, you might have to learn how to wark with sreadsheets, and that's ‘when knowing osenpyxl comes in handy! ‘Spreadsheets are avery intuitive and user‘riendly way to manipulate arge datasets without any prior technical background, That's why they're still so ce inthis article, you'l earn how touse Improve Your Python sith afresh Python Trick code snippet every couple of days: * Manipulate &cel spreadsheets with * Extractinformation from spreadshe + Create simple or mare complex spre Email Address Thisarticleis writen for intermediate de as dicts and ists, but also feel comfortab Download Dataset: Click here to download the dataset for the opennyxl exercise you’ILbe following in this tutorial. aT ras Learn Python » erences Before You Begin you ever get asked to extract some data from a database or log ile into an Excel spreadsheet, orf you often have to convert an Excel spreadsheet nto some more usable programmatic form, then tis tutorial is perfect fr you. Let's Jump into the eperpya caravan! Practical Use Cases First things frst, when would you need to use a package like opensysi ina real-world scenario? You'llsee afew examples below, but really, there are hundreds of possible scenarios where ths knowledge could come in handy. Importing New Products Into a Database ‘You are responsible fr tech nan online store company, and your boss doesn’t want to pay fora cool and expensive (CMS system Every time they want to add new products othe online store, they come to you with an Excel spreadsheet with afew hundred rows and, for each of them, you have the product name, description, price, and so forth Now to import the data, you'll have to iterate over each spreadsheet row and add each product tothe online store Exporting Database Data Into a Spreadsheet Say you havea Database table where you record al your users nformation, including name, phone number, emai address, and s0 forth Now, the Marketing team wants to contact all users to give them some discounted offer or promotion. However, they neat bos aneot-nitle In the code above, you frst open the spreadsheet sarpie.xisx using Loa¢_norkbooe(), and then you can use workbook. sheetranes to See allthe sheets you have avalableto work with. After that, workbook. active selects the fist avalable sheet and, inthis case, you can see that it selects Sheet 1 automatically, Using these methodsis the default ‘way of openings spreadsheet, and you'l see it many times during this tutorial, Now, after opening spreadsheet, you can easly retrieve data from ilk this: oop sheet a0") cee Improve Your Python boy sheet“"] valve marketplace’ .with afresh 3 Python Trick & code snippet every couple of days: boo sneet'F10"] valve Dpeteveny coupiect day ° Email Address Toretuen the actual value ofa cell you n the method .cei1()toretrievea cell usin ett object: columns) value You can see that the results returned are the same, no matler which way you decide to go with. However, inthis tutorial, youl be mostly using the first approach: (“42 Note: Even though in Python you'e used toa zero-indesed notation, with spreadsheets you'll always use a ane indexed notation where the est row or column always has index, ‘The above shows you the quickest way to open a spreadsheet. Hovever, you can pass addtional parameters to change the way a spreadsheets loaded Additional Reading Options ‘There ae afew arguments you can pass to 024 workoook() that change the way a spreadsheet is loaded. The most Important ones are the following two Booleans: 1. read_only loads a spreadsheet in ead-only mode allowing you to open very large Excel les. 2. data_only ignores loading formulas and instead loads only the resulting values, Learn Python With a Community of Experts » Importing Data From a Spreadsheet 'sabout time you get tothe fun part: the iterate Now that you've learned the basics about leading a spreadsheet, and actual usage of the values within the spreadsheet, This section is where you'l learn all the different ways you can iterate through the data, but alse how to conver that data nto something usable and, more importantly, ow to doit ina Pythonic way Iterating Through the Data ‘Thete area few different ways you can iterate through the data depending on your needs, You can lice the data witha combination of columns and rows: ooo meet a02° (ecole >, cell “Sheet 102, Cell “Sheet 11D)) ‘You can get ranges of rows or columns: Improve Your Python sith afresh 83 Python Trick code snippet every couple of days Email Address Doo ance" (colt "sheet 1.82, Geld “Sheet 1° 42005) Do> sheee("A:0"] (Cece “Shoes 21-8, ell “Sheet £°/A1065), colt ‘Shoes 2181869)) D> eet] (cold “sheet 1.459, ell ‘Sheet 1.059) >>> set 5:6 ((ecend “Sheet 285, Scehh “Shoes 2-08), Improve Your Python Seen “Sheet $2065) sith afresh 5 Python Trick ode snippet every couple of days: You'l notice that alo the above exp ‘tuples in Python, check out the article or Email adress There are also multiple ways of using nor use to achieve this are: + ster_rous0) ‘oth methods can receive the fllowing arguments ‘These arguments are used to set boundaries forthe iteration: saceote} prinstomd Gece Sheet rh, ol) “Shee 18>, cel ‘See 32.) (cee “shest ab), ell “Shet 189, cel “Sheet 316) 29 for colum in she. iter cols(aln raed, nax_col-3) Lr pinetctunny (ett “Sheet 1°42, cel “sheet 1°40) (coll ‘sheat 171329, cco "sheet 2.829) (cell ‘heat 1".C>, cel "sheet 1.0) ‘You'll notice that inthe frst example, when iterating through the rows using .iter_rows(), ou get one vpte element per row selected While whenusing ite instead «cels() and iterating through columns, youl get one uote per column ‘One additional argument you can pas ofthe cell are retumed, instead ofthe col object: both methods is the Boolean valves_only, When it's st to >> for value in shect.Ster_rovs(ain rot, valuesonly-True prinetvatue) Cnarcerpiace', ‘curtoror_te', ‘ceview td") Cust, ssn, "s309sczeveev7s') you wantto iterate rough the whole dataset, then you can also use the at butes.rons oF columns directly, which ae shortcuts to using .ter rst) and. rytnon Improve Your Python sith afresh Python Trick ce1t "Shoot 2 code snippet every couple of days: princteow) (ett “Sheet 1a Gell “Sheet 1° M09», CELL “Sheet f Email Address Thes e shortcuts are very useful when you Manipulate Data Using Python's Default Data Structures Now that you know the basis of iterating through the data in a workbook, e's look at smart ways of converting that data into Python structures ‘As you saw earlier, the result from all iterations comes inthe form of tuples. However, since a tape is nothing more than an immutable 1sst, you can easly access data and transform itinto other structures. For example, say you want to extract product information from the saple.xisx spreadsheet and into a dictionary where each keyis 2 product! A straightforward way to do thst iterate overall the rows, pick the columns you know are elated to product information, and then store that na dictionary. Le’ code this out First ofall, have alook atthe headers and see what information you care most about: Pytbon wstntn rows, values_only-tru) peinttvatue) This cade retuins alist of all the column names you haven the spreadsheet. To start, grab the columns with names Lucky for you the columns you need are all nextto each other sa you can use the nin. get the data you want: ws{nin_row2, Values_only-tru): printtvetue) (Canoraveazc', 937801378, “Invicta Wonan\'s 45150 “Angel® 28K Yellow...) (Cunaoancone", 4ngn10722; “Kenneth ole New York Koren's KER...) ‘Nice! Now that you know how to get ll the important product information you need e's put that data inte 8 dictionary oor Seon orton - lond_worthoa(¢Slerane-"soapl6.41 68") see sae hee otbteinrees, Improve Your Python tense with afresh 3 Python Teck Valves ol ode snippetevery couple of days: = vou) © ta Email Address ‘seie": row[2], category"? row , productefproduct_id) - product ‘Using json tere to be able to format the o Prine (Json.cinpe(pracucts)) or etsplaying Later ‘The code above returns a JSON similar to this: son wooracorze": Here you can see that the output is trimmes to 2 products only, but ifyou run the script ast, then you should get 98 products Convert Data Into Python Classes Tofinalize the eading section ofthis tutorial, let’ dive into Python classes and see how you could improve onthe example above and bette structure the data, For this, you'll be using the new Python Data Classes that are avaliable from Python 27. you're using an older version of Python, then you can use the default Clases instead. So, ist things first e's look atthe data you have and decide what you want ta store and how you want to store it, /As you saw right at the start this data comes from Amazon, and itsalist of product reviews. You can check thelist of nsand their meaning on Amazon, ‘There are two significant elements you cn extract from the data available 2 Products 2 Reviews A Product has +0 = Tile + Parent + category The Review has few more elds +p * Customer ID Improve Your Python + stars ne nnn 2 Pian i ippet every couple of ay * Date Email Address You can ignore afew ofthe review fields So,a straightforward implementation of ‘Mier defining your data classes, you need to conver the data fom the spreadsheet into these new structures Before doing the conversion, is worth looking at aur header again and creating mapping between columns and the fields you need ‘aloes_oy-Tru): printtvstue) Cnareetpiace', "custorer te, "sevien i, “produc doo for cell in sheet] print(cell value) Lets create aflenapoing.oy where you have alist of ll the feld names and their column location eer the spreadsheet: indexed) on 4 sevice tits Improve Your Python sith afresh Python Trick code snippet every couple of days: feview_pare ~ 14 Email Address You don'tnecessariy have todo the map end up with alot of magic numbers ying Finally let's look atthe code needed t parse the spreadsheet data into alist of product and review objects teridook = ond wribook(lenmes"stnple. ale, read oly) : products = (] for rou in sheot.A20-_rour(ninrom-2,lUes_oly-Tras) product = Product{ideron{PRODC10), parenteron[PROGUC. PARES], e-rom[ POET TITLED, ategory-ron[ PRODICT_CATECORY)) products. 2ppenatproduct) arsed_date - catetine.steptine(spread date, "AV-21-44°) roviou = Reviow(scorou[REVIEK 10], “custener_sgorau( EVTEM_CUSTONER), starssrou[fEVIEM STARS), heal nero EVE HEADLINE), odyerow(REVEEW 8007), dave-parsed date) reviews sppend(revien) prine(pracuets(0]) Princtrevsews(@1) ‘Mer you run the code above, you should pet some output ike this: Procuct(ie='E00FALOIZC', parent-OS7861378, «-.) (ide ROOSGLEVQWVIE, custonen 14353802, ..) nats it Now you snouta nave me a2ta in avery simp ana aigestibie class formar, and you can start tninaingot storing ths na Database or anyother type of data storage you like, Using this kind of oP strategy t “| don’t even feel like I’ve scratched the surface of what I can do with Python” a parse spreadsheets makes handling the data much simple later on Otros Appending New Data Improve Your Python Before you start creating very complex st with afresh Python Trick ‘sting spreadsheet. ode snippet every couple of days oback othe fist example spreadsheet Coit ke this: Email Address fron openye ingort laa. sorkbook orktook~ Teae_sortnonk(fSlenare-"helo-sorié lee") sheet ("C2") = "writing 2) orktooksave(#slen Exvoil, if you open the new hel1o_worid_sppend.xisx spreadsheet, you'l see the following change: Notice the addtional writing on celle. Writing Excel Spreadsheets With openpyxl ‘There area lt of different things you can write toa spreadsheet, rom simple text or number values to complex formulas, charts, or even images. Lets start creating some spreadsheets Creating a Simple Spreadsheet Previously, you saw a ery quick example of howto write “Hello word” into a spreadsheet, so you can start with that Improve Your Python sith afresh Python Trick code snippet every couple of days: Pytbon Email Address openpy tnport Morktook ‘slorane = chelie-sorie.siow workbook = Workbook) sheet = wortbooeactive sheet ("81") sheett"61"] sorebaok.save(#lenanes¢¥lenane) ‘Thehighlighted lines in the code above are the most important ones for writing. Inthe code, you can see that + Line s shows you how to create a new empty workbook *+ Lines 8 and 9 show you how to add data to specific call + Line 12 shows you how to save he spreadsheet when you'te done. Even though these lines above canbe straightforward, its stil ood to know them wel fer wher complicated ings get abit more Note: You'll be using the hel2e_word.xsx spreadsheet fr some ofthe upcoming examples, so keep it handy. (One thing you can do to help with coming code examples is add the following method to your Python file or console: >o> ef princes) For raw in sheet. Ster_rows(values_only=True): prinstrou) Iemakes it easier to print all ofyourspreadsheet values by just calling print_rows() “I wished I had access to a book like this when | ‘ane lemngyiton many yur oe" —Mariatta Wijaya, CPython Core Developer, Ofenes Basic Spreadsheet Operations Before you gt into the more advanced topes, it's good for you to now how to manage the most simple elements of a spreadsheet. Adding and Updating Cell Values You altendy teamed how to add values ta snreadsheot ke boo sneee["A2"] = "va There's another way you can do this, by ist selecting a cell and then changingits value Improve Your Python = sith afresh 5 Python Trick bee etl = sheett"61] ode snippetevery couple of days: » * Email Address Thee value is only stored into the spreadsheet once you call workbook. save, ‘The openpyal creates 3 cell when adéinga value ifthat cell didn't exist before: Pon 25> prtme_rowe() Celio", ‘worie") >s> sneet["aie"] = "test >>> prem rouse) (Cette, rit") (Gone, one) (Gone, None) (Gone, None) (Gone, None) (pone, sone) (Gone, None) (Gone, None) (Gone, sone) (Gone, "eeet") ‘As you can see, when trying toad a value to cell ste, you end up with a tuple with 10 rows, just so you can have testvalve, Managing Rows and Columns ‘one ofthe most common things youhave todo when manipulating spreadsheets is adding orremoving ows and columns. The openpyxt package allows you to do that n avery straightforward way by using the methods: + sansere_rows() + sdetete rows() + sansere cats) + sdetete cots() very single one of those methods can receive two arguments: Lisa 2 anount os» préne_rowe() Crelto', Horie) Improve Your Python >>> sheet-insert_cots(Ldee2) bso prine_rows() (Gone, ‘hele, ‘workel") sith afresh Python Trick code snippet every couple of days: Email Address >os aneet-insengcole(ie-s, sour! >>> prtne_rousc) (Gone, "hello", Nore, None, None, Nor 23> meee dete. cole(‘ee-3, seu) >>> see. dete, cols(e-2) >>> prene_rous() (Creliet, rie") D> sheet. insert_rows(it-2) >>> prane_roust) (one, sone) Crete", ‘wortel") >>> seet-Insant_ronslee-, anount-3) >>> patne_rousc) (Gone, sane) (Gone, None) (Gone, sone) (Gone, sone) Chelios, wort") >>> sheet dete rows(Ldt-1, anount=s) Doo prine_rows() Crelio', ‘orié!") ‘The only thing you need to remembers that when inserting new dat before the scx parameter (rows or columns), the insertion happens o,f you do snaer trowe(2), inserts anew row before the existing fist row. I's the same forcolurnns: when you call nsert_cots(2), it inserts anew column right before the already existing second column (3). However, when deleting rows orcolumns, delete... deletes data starting from the index passed as an argument, For example, when doing deLete_rows(2) it deletes row 2, and when doing gelete_cods(3) it deletes the thiré column a. Managing Sheets ‘Sheet management i also one of those things you might need to know, even thought might be something that you don*tuse that often Ifyou Took back atthe code examples rom this tutorial, you'l notice the following recurring piece of code: Thisisthe way to sel sheets, then you can always selec a speciicone ike this: Pynon [Moraducts', ‘conseny sales’ 299 preducts_sneet = workbook "?=odue >>> sates_sreet = wockbool "Conary £ You can also change sheet title very eas Croraducts', ‘Conseny sae [ven Prosicts', “Conny Sales"T Ifyou want to create or delete sheets, then you can also do that with .reate_sneet() and Pyton Voreducts', ‘Conan sates sheet "operations") [-Preauces', "Conary Sates", “Qperations") >>> hee = workbook create sheet (IR, 2) Tim, ‘products’, "Company sales", ‘operations >>> workbootrenovefopeaions_shet) ['ie, "Products", ‘company Sale nent to the .renove() >>> workbonk renove(nr_sheet) [-Proaucts', ‘Conny sates (One other thing you can dois make duplicates ofa sheet using copy vorksheet() >>> produers_sneet ~ wosookl "Posies" >>> workbook copy socket (oreducts_ sheet) [oroduees', ‘Conary Sales’, "Products copy the dfault sheet from a spreadsheet. However, you're opening a spreadsheet with multiple Improve Your Python sith afresh Python Trick code snippet every couple of days: Email Address renovet) you open your spreadsheet ater saving the above code, you'll notice that the sheet Products Copy isa duplicate of the sheet Products. Froazina Bae and Caliimne Freweng news aru Gumus ‘Something that you might want to do when working with big spreadsheets is to freeze afew ros or columns, so they remain visible when you seroll right or down, Freezing data allows you to keep an eye on important rows or columns, regardless of where you scrolin the spreadsheet. ‘Again, openpyn also has away to accomplish this by using the worksheet freeze_panes attribute. Fr this example, go back to our saotex1sx spreadsheet and try doing the folowing: >> verbo = Lond hk Lanane Improve Your Python >>> sheet freete panes = °C sith afresh Python Trick > serena ve foten xl) ede snippet every couple of days EmailAddress Ifyou open the sanple_froren.xlex pres columns and are rozen and are alway This Features handy, for example, to kee Here's how't looks in the editor: Notice how you're atthe end ofthe spreadsheet, and yet, you can see both row and columns aands. Adding Filters You can use opanpyx to ade filters and sors to your spreadsheet. However, when you open the spreadsheet, the data won't be rearranged according to these sorts and fiers, ‘Atfirst, this might seem lke a pretty useless feature, but when you're programmatically creating a spreadsheet that is going to be sent and used by somebody else it's stll nice to at least create the fiters and allow people to useit akerwars The code below isan example of aw you would add some fiters to our existing sanpie. xlsx spreadsheet: D> workbook save(FLtenane"sa eh tatters se") You should now see the ‘created when opening the spreadsheet in your editor: Improve Your Python sith afresh Python Trick code snippet every couple of days: Email Address You don’thave to use sheet. cinenstons if you know precisely which part of the spreadsheet you want to apply ters ae a Your Practical Introduction to Python 3 » Oemeeads Adding Formulas Formulas (or formulae) are one ofthe most powerful features of spreadsheets ‘They gives you the power to apply specifi mathema assimple as editing the value ofa cel equations toa range of els. Using formulas with openpyx is You can ee the ist of formulas supported by Frovenset((*A85", rest") Lets add some formulas to our sanpe.x) Improve Your Python Starting with som ing easy, let'scheck sith afresh 83 Python Trick Pyton code snippet every couple of days >>> sheet"92"] = “AVERGE(H2:H109) Email Address >>> wreak save(FlZenane-"sorte fe It you open the spreadsheet now and go the editor You can use the same methodology to add any formulas to your spreadsheet. For example, e's count the number of reviews that had helpful votes: >>> sheee["23"] = "acouurie(12s1208, "0°) 29> workbook. save(ilenane-"sane formas se") ‘You should get the number 21 on yourPs spreadsheet callie so: Improve Your Python sith afresh Python Trick code snippet every coupe of days: ‘You'll have to make surethat the strings) peeeeey PEE {quotes around the formula kein the ex acount (2221208, \"98\")" Email Address There ateaton of other formulas you car go yourself Adding Styles Even though styling spreadsheet might not be something you woule do everyday it's stil ood te know howto do Using openpyx, you can apply multiple styling options to your spreadsheet, including fonts, borders, colors, and so ‘on. Have a look at the openpyx cocumentation to learn more, You can also choose te either apaly a style dire call, ly toa cellorcreate a template and reuse to apply styles to multiste Lets star by having look at simple call styling using our sanpie.xtsx again asthe base spreadsheet Pon ~ 23> bond fant = Fone(balsersc) 25> ig ned_toxt ~ Fone(color-colons 86, 120-28) >o> canter aligned, text = ALAgoent(horLzontal-“center") 59> aouble_border Hide = Size(barder_styles'soubie") 255 squane_porder”» Border(rop-dovle_ ponder, Left-double_porder side) | 95> sheet {"22"] font « bold font 25) aneee["03"T fone = igre ext >>> sheet "At" aligment = centered text D> sheet["AS"] Border = square, borer 29) workbook save onan rspie syles dex) Ifyou open your spreadsheet row, you should sce quite a few different styles onthe first 5 cells of eolurnn a Improve Your Python sith afresh 83 Python Trick code snippet every couple of days: Email Address ‘There you go. You gt + Azwith the text in bold ‘+ Aawith the ext inree ane bigger font size + Amwith the tert centered + ASwitha square border around the text Note: For the colors, you can also use HEX codes instead by doing Font(colors*c7#E8F°) You can also combine styles by simply adding them tothe cell atthe same time: 25> mneee["Ae"] alignment = cantor aligned ext 55> sheet A6"] font = big red text D> sheec["AC"] Border = sue, border 299 workbook save Flonase sylen es) Have alook atcellas here: Improve Your Python sith afresh 83 Python Trick code snippet every couple of days: When you want to apply multiple styles ® pe Pieotaay style template that you can use over and " “ Email Address >>> header = NanedStyle(nanes"besce Do> header font = Fent(belds eve) 25) haadar border = Border (botzonSiae(honder_style="t56")) >>> header allgmnert = Aligment{harizortal="certer", verticals*center") >> # Wow let's apply this to ald First row (header) celts >>> neader.row = sheet(2} >>> workbonk save( filenane"same eyes ai) Ifyou open the spreadsheet now, you should see that its ist row is bold, the texts aligned tothe center, and there's small bottom border! Have a look below: ‘As you saw above, there ae many options when it comes to styling, and it depends on the use case, so fel fee to ‘heck openpyxt documentation and see what ather things you can do, SI Ru acura ar etl Pentre EL Cst arnt rd Oneness Conditional Formatting Improve Your Python This feature is one of my personal favorit anith afresh @ Python Trick © code snippet every coupe of days: lesa much mare powerful approach tost spreadsheet changes Email Address Ina nutshell, conditional formatting alle specific conditions. For example, a widespread usecase Ist nave a balance sheet where all the negative totals are in rea, and the postive ‘ones aren green. This formatting makes it much more efficient to spot good vs bad periods. Without further ado, let's pick our favorite spreadsheet™ranpie.xlsx—and add some conditional formatting You can start by adding a simple one that add a red background to allreviews with less than 3 stars: >> ree_background ~ patteenF311(bgColor-colors.RED) ooo aiff style = Dieferensilstyle(il-re background) 235 rule™= fule(sype"oxpronsion, ef-eiff_syle) >>> rue. foomula = (-$:2<3"] Doo sheet-canditionsl formating edd(":0100", rae) 295 workbook saves conditional formatting 30°) Now youll see al the reviews with star rating below 3 marked with a red background: CCose-wis, the only things that are new here are the objects bs ferensialstyle and Rule + oistenenttarstyieis quite similar to Nanedstyte, which you already saw above, and it's used to aggregate multiple styles such as fonts, borders, alignment, and so orth, + nateis responsible for selecting the cells and applying the styles ifthe cells matehthe rule's logic Using anute object, you can create numerous conditional formatting scenarios. However, for simplicity sake, the openpyxl package offers 3 bultsn formats that makeit easier to create a few ‘common conditional formatting patterns. These built-ins are ve Improve Your Python © DataBar .with afresh 3 Python Trick S code snippet every couple of days: The ColorSeale gives you the ability ocr Pen Email Address ‘nd color-colors GREEN) >s> snentconditionn_foraaingad('0:H190", colon seale_rule) >>> workbook save(FLLenanes"sarle.condttionl” Footing color scale xlsx") ‘Now you should se a color gradient on column rom red to green, according to the star rating You can also add a third color and make two gradients instead o> colon senlerale = Colorsaletle(start_types"nut >>> sheet-conditional foreatting add 28100", color scale rule) >>> werkbook save(Filenane "same conditional formating lor seale 3.2153") Thistime, you'l notice that star ratings 6 Improve Your Python 3 and Shave gracient from yellow to gr sith afresh 83 Python Trick code snippet every couple of days: Email Address TheleonSet allows you to add an icon tothe cll according tots value: Do> eon set pute = LeanSettule(Seravs, “ny [hy 2,3, 46 SDD 23> mnees-conditional forasteing.246('0:4090", Leon set_ule) >>> workbook save("sapele_conaitional formatting i You'lsee a colored arrow next tothe star rating. This arrow i ed and points down when the vale ofthe cellis1 nd, asthe rating gets better, the arrow stats pointing up and becomes green: Improve Your Python sith afresh 3 Python Trick code snippet every couple of days: Email Address ‘The openpyxd package has a ullist of ther icons you can use, besides the strow. Finally, the DataBar allows you to create progress bars: color-colors. EEN) D>) sheet-condttional formatting add(12:1500", data, bar rue) 2o> workbook, save("sampe conditional, formating data, baraxlax") You'll now seea green progress bar that gets fller the closer the star ratingisto the number: Here, you saw only afew examples of what you can achieve with it but check the epenpyaa documentation to see bunch of ether options. Nae Le Otenoseais Adding Images Improve Your Python ven though images ate not something t with afresh 2s Python Tick “Maybe you can use it for branding purpo: code snippet every couple of days: Tobe abet load imagesto.aspreadshe ee Email Address set pip inten, putin ‘Apart from that, you'lalso need an image. For ths example, you can gra the Real Python log below and convertit from .webo to 2ng using an online converter such as feck. cam, save the final le as Logo.png, and copy ito the oot folder where you're running your examples: ‘Afterward, this isthe code you need to import that image into the netto_word. lax spreadshest orktoot = Toad sertooak(fSlenare."hel20 worné.xlex") og0 = Image(“Ioe0. 26") shoet.3_inage( 062, °83") jorktookSave(#ileranes"hello,}0r1d_Logo.Xlse") You have an image on your spreadsheet! Here it is: Improve Your Python sith afresh Python Trick code snippet every couple of days: ‘Theimage’s leh top comerison the cells Email Address Adding Pretty Charts ‘Another powerful thing you can do with spresasneetss create an inreaibievanety ot cnars Charts are a great way to visualize and understand loads of data quickly. There area lat of diferent chart types: bar chart, pie char, ine chart and so on. openoyx has support for a lotof them Here, youl see only a couple of examples of charts because the theory behind it isthe same for every single chart ‘ype Note: A few ofthe chart types that open currently dogsn't have suppor for are Funnel, Gant, Pareto, ‘Treemap, Wateral, Map, and Sunburst. For any chartyou want to build, you'll need to define t tobe used forthe chart, whichis called Reference. 1 chart type: darchart, Linechrt, and so forth, pls the data Before you can build your chart, you need to define what data you want to see represented init. Sometimes, you can Use the dataset ais, ut othertimes you neec to massage the dats abit to gt adeitional information, Lets start by building a new workbook with some sample data: workbook = Workbook() [Pereduet*s “ontine's "Store" Lh, 4s), 12, «9, 301, (3, 49, 25), is se, Is, 36, {sr 2s, 17 2, a, 1 sheet 2ppendtrow) [Now you're going to star by creating bar chart that display the total number of sales per product: chart = narcnart() ~ Reterence(woreshees-shees, chart.a6d cata(data, tithes. sheet aud enare(enare, "E2") om dats-Trve) ordbook save("chart.xl5i°) ‘There you havelt. Below, you can see ay. sales online and instore product sales: Improve Your Python sith afresh Python Trick code snippet every couple of days: Email Address ike with images, the top left comer ofthe chart i on the cell you aeded the chart to. In your eas, ft was on cell e2 Note: Depending on whether you're using Microsoft Excel or an open-source alternative (ibreOffce or ‘Openoffice, the chart might look slightly citferent. Ty creating line chart instead, changing the data bt: sorkbook = Workbook) (Ep “Danuary's "Feary, eh "ape Novenber", “Secenber"], shoct.sepend(rou) snax_col-13); fell.value = randon-randrangetS, 280) With the above code, you'll be able to generate some random data regarding te sales of ferent products across 3 whole year. (once thats done, you can very easly te Improve Your Python yen with afresh 23 Python Trick ode snippetevery couple of days: a tetera, pai ative tense) chartadd_data(date, from fousclruc, cates ere sheet aed enare(enart, "C5") sorebook.save( "Line chart tse) Here's the outcome ofthe above piece of code: (One thing to keepin mind heres the fact that you're using éron_rouserrve when adding the data, This argument ‘makes the chart plot row by rou instead of column by columa, In your sample data, you se that each product has a row with 12 values (1 caluma per month) That's why you use ‘rom_rons. you don't pass that argument, by default the chart tries to pla by column, and youl get a month-by- ‘month comparison of sales. hat our eference now starts from the ‘nother diference that has to do with the above argument changes the fat first column, nin_col-s, instead ofthe second one. This changes needed because the chart now expects the fist column tohave the titles, There area couple of other things you can also change rega specific categories tothe chart cats = fararence(uorksheet-sheet, tones) chart. set_categories(cats) Add this piece of cade before saving thes umber: Improve Your Python sith afresh 83 Python Trick © code snippet every couple of days: Email Address CCode.wise,thisisa minimal change. Sutin terms of the readability ofthe spreadsheet, this makes it someone o open the spreadsheet and understand the char straightaway. ch easier for ‘Another thing you can do to improve the chart readabilty isto add an ans. You can doit using the attributes x axis andy acs chart. yaxis.title » “Sales (per w ‘This wil generate 2 sreadsheet like the below one: Improve Your Python sith afresh 83 Python Trick code snippet every couple of days: Email Address ‘As you can see, small changes like the above make reading your chart a much easier and quicker task ‘Theres also a way to style your chart by using Excel's default uartsty2e property. In this case, you have to choose a ‘number between 1 and 48. Depending on your choice, the colors of your chart change as wel With te style selected above, all ines have some shade of range: ‘There isno clear documentation on what each style number looks like, but this seadshet has afew examples of styles availabe Complete Code Example Show/tlide ‘There area lot more chart types and customization you can apply so besureto checkout the packa documentation onthisif you need some Improve Your Python Python Tricks The Boo eee with a fresh 2 Python Trick © ‘eto Fee su code snippet every coupe of days: Okemoveads Email Address Convert Python Classes to ‘You already sawhow to convert an Excel. Let's imagine you have 2 database and are using some Object Relational Mapping (0M) to map DB objects into Python classes. Now, you want to export those same objects int a spreadsheet, Let's assume the fllowing data classes to represent the data coming rom your database regarding product sles festa tales: List{Sale] "Now, let's generate some random data, assuming the above classes ae stored in a h_classes.p le - tgrove these for row, You'TL use then in 3 506 3) products = C1 fate wnt of Improve Your Python sale = Sale(quantity-rane anith afresh 3 Python Trick © ses. 2ppena(sale) code snippet every couple of days: trict «Prams (6) mail address procuctssppenatoroduct) By running this piece of code, you should get 5 products with 5 months of sales with a random quantity of sales for leach month "Now, to conver this nto spreadsheet, you need t iterate over the data and append itto the spreadsheet: orebook = workbook) 1 Sopend column nares first sheet. append(["Procuct 10", "Preduct ane", "nth 2" oath 2", “Ronth 3°, "Moreh 4°, "Montn’5°)) + bopand the eat fate = [product id, product. nave] sata. append(sale-quontsty) shoot sppend(ésts) ‘That's it. That should allow you to create a spreadsheet with some data coming from your database. However, why not use some ofthat cool knowledge you gained recently to add achartas wellto display that data more visually? Alright, then you could probably do something like this: Python aet » Linechart() sefererce(voreshact-ste snax_col-7) shart.a6dcata(eats, ties. fron rouserruc) sheet.2ed_cnare(enart, "60") chart.set_categories(eats) RENE Nae 2 nee foe Improve Your Python sorebooksave(ilenanes"029 snp sith afresh Python Trick code snippet every couple of days: Now we're talking! Here's a spreadsheet . " ' Email Address That'sa great way for you to wrap up your new knowledge of chars! Bonus: Working With Pandas ven though you can use Pandas to handle Excel files, there are few things that you ether can't accomplish with Pandas or that you'd be beter oust using openpyl directly For example, some ofthe advantages of using openpyxd are the ability to easly customize your spreadsheet with styles, coneitiona formatting, nd such, But guess what, you dan'thave to worry about picking. In fat, openayxi has suppart for both converting data from a ‘Pandas DataFxame into a workbook or the opposite, converting an osenpyad workbook into a Pandas DataFrame, Note: fyou're new to Pandas, check our course on Pandas Dalaframes beforehand. First things fist, remember to install the pandas package: S pip Snstalt pandas Then, let's createa sample DataFrame: aor Product Nane": ("Product 1", "Product 2"Jy Sales Porth 1°: [18, 28], alee vorth 2°: [5 35], > GF = pd.oatatrane(ésts) Now that you have some data, you can ut Improve Your Python pytion with afresh 3 Python Teck on code snippet every couple of days: Email Address sorkbook = Workbook() sheet. append(row) _ronsta, oreo, save("pandss. x8") You should see spreadsheet that looks lke this Ifyou want to add the DataFrame’s index, you can change Sndex-rrve, and it adds each row’ indexinto your spreadsheet. Con the other han, fyou want to convert a spreadsheet into @DataFrame, you can als doit ina very straightforward vay likes: orktook = Toud_sorthook(¢Slenanes"sanple.¥15e") F = pe.oatarrana(vaiues) Altematively, i you want ta add the correct headers and use the review ID asthe index, for example, then you can also Coit ike this insteae verktook = Toad_wortbook(¢UTenane-"st S rtbeak seive Improve Your Python shen rales sith afresh 5 Python Trick code snippet every couple of days: cole = nox(eats) fats = Tevteats) EmallAddress f= pe.oatsFrara(eats, index-ios, cov Using indexes and columns allows you to access data fom your DataFrame easly ext nae erypesanfect") 23> aff stan rating 120 sossczmv06\76 5 RengrOLINETIG—S D> # Grab review with 1¢ “RREQLVILGENCS", using the Index >>> of loc R2EQLIVIEF8C9"] Sevienid. s2raavaueecy None: ARELIVLLEEOC, type: object Improve Your Python sith afresh Python Trick There you go, whether you want to use ot code snippet every couple of days: algebra, you now know how to suitch be Email Address Te ures ene Conclusion Phew after that long read, you now knox how to work wth spreadsheets in Python You cn rely on opengy, your trustworthy companion, t: + ctract valuable information frm sareadsheetsin a Pythonie manner + Crete your own spreadsheets, no matter the complexity level + Add cool features such as conditional formating or charts to yourspresdsheets There area few ther things you can do with penpy that might ot have been covered this tutorial butyou can always check the package's official dacumentation website to learn more aboutit. You can even venture into checkingits sourcecode and improving the package further, Feel free to leave any comments below if you have any questions, orf there's any section you'd love to hear more about. Download Dataset: Click here to download the dataset for the opennyxl exercise you'll he fllowing in this, tutorial, Markas Completed GI (TTD This tutorial has a related video course created by the Real Python team. Watch ittogether with the ‘written tutorial to deepen your understanding: Editing Excel Spreadsheets in Python With onenpyxl B® Python Tricks A Get a short & sweet Python Trick delveres to your inbox every couple of days. No spam ever. Unsubscribe anytime. Curated by the Real Python team, About Pedro Pregueiro wilt Improve Your Python tr. sith afresh 83 Python Trick code snippet every couple of days: Email Address Each tutorial at Real Python is created by a team of developers so thatit meet our high quality standards. The team members who Master Real-World Python Skills With Unlimited Access to Real Python Join usand get access to hundreds of tutorials, hands ‘on video courses, and a community of expert Pythonistas: —«uee ;; 0) What Do You Think? (Ere) (Fae) (Bea) Real Python Comment Policy: Te most useful comments are those written with the goal of learning from orhelping out other readers—after reading the whole article and all the earlier comments Complaints and insults generally won't make the cuth~ What's your i takeaway or favorite thing you learned? How are you going to put your newfound sls touse? Leave a comment below and let us know. Keep Learning Related Tutorial Categories: (armada) Recommended Video Course: Eitng| Improve Your Python sith afresh 83 Python Trick code snippet every couple of days: ( Nospam, Unsubseribe anytime, faerie sel se) Table of Contents + Before Reading ce Spreadsheets With openpyal Improve Your Python sith afresh Python Trick code snippet every couple of days: Email Address ‘Pylhon Tutorials Search - Privacy Policy: Energy Palicy- Advertise - Contact ‘© Happy Pythoning!

You might also like