Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Convert CSV to Excel xlsx in Python

#1
Convert CSV to Excel xlsx in Python

5/5 – (1 vote)

Problem Formulation


? Challenge: Given a CSV file. How to convert it to an excel file in Python?

csv to excel in Python

We create a folder with two files, the file csv_to_excel.py and my_file.csv. We want to convert the CSV file to an excel file so that after running the script csv_to_excel.py, we obtain the third file my_file.csv in our folder like so:


All methods discussed in this tutorial show different code snippets to put into csv_to_excel.py so that it converts the CSV to XLSX in Python.

Method 1: 5 Easy Steps in Pandas


The most pythonic way to convert a .csv to an .xlsx (Excel) in Python is to use the Pandas library.

  1. Install the pandas library with pip install pandas
  2. Install the openpyxl library that is used internally by pandas with pip install openpyxl
  3. Import the pandas libray with import pandas as pd
  4. Read the CSV file into a DataFrame df by using the expression df = pd.read_csv('my_file.csv')
  5. Store the DataFrame in an Excel file by calling df.to_excel('my_file.xlsx', index=None, header=True)
import pandas as pd df = pd.read_csv('my_file.csv')
df.to_excel('my_file.xlsx', index=None, header=True)

Note that there are many ways to customize the to_excel() function in case

  • you don’t need a header line,
  • you want to fix the first line in the Excel file,
  • you want to format the cells as numbers instead of strings, or
  • you have an index column in the original CSV and want to consider it in the Excel file too.

If you want to do any of those, feel free to read our full guide on the Finxter blog here:

? Tutorial: Pandas DataFrame.to_excel() – An Unofficial Guide to Saving Data to Excel

Also, we’ve recorded a video on the ins and outs of this method here:




Let’s have a look at an alternative to converting a CSV to an Excel file in Python:

Method 2: Modules csv and openpyxl


To convert a CSV to an Excel file, you can also use the following approach:

  • Import the csv module
  • Import the openpyxl module
  • Read the CSV file into a list of lists, one inner list per row, by using the csv.reader() function
  • Write the list of lists to the Excel file by using the workbook representation of the openpyxl library.
  • Get the active worksheet by calling workbook.active
  • Write to the worksheet by calling worksheet.append(row) and append one list of values, one value per cell.

The following function converts a given CSV to an Excel file:

import csv
import openpyxl def csv_to_excel(csv_filename, excel_filename): # Read CSV file csv_data = [] with open(csv_filename) as f: csv_data = [row for row in csv.reader(f)] # Write to Excel file workbook = openpyxl.workbook.Workbook() worksheet = workbook.active for row in csv_data: worksheet.append(row) workbook.save(excel_filename) if __name__ == "__main__": csv_to_excel("my_file.csv", "my_file.xlsx")

This is a bit more fine-granular approach and it allows you to modify each row in the code or even write additional details into the Excel worksheet.

Where to Go From Here?


Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

? If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



https://www.sickgaming.net/blog/2022/06/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Convert MIDI to MP3 in Python – A Quick Overview xSicKxBot 0 2,395 09-02-2023, 02:04 PM
Last Post: xSicKxBot
  [Tut] How to Convert an Octal Escape Sequence in Python – And Vice Versa? xSicKxBot 0 1,336 12-08-2022, 01:23 PM
Last Post: xSicKxBot
  [Tut] How to Convert Octal String to Integer in Python xSicKxBot 0 1,301 12-04-2022, 08:39 AM
Last Post: xSicKxBot
  [Tut] Python Convert Hex to Base64 xSicKxBot 0 1,278 11-30-2022, 09:32 PM
Last Post: xSicKxBot
  [Tut] How to Filter Data from an Excel File in Python with Pandas xSicKxBot 0 1,227 10-31-2022, 05:36 AM
Last Post: xSicKxBot
  [Tut] How to Convert Bool (True/False) to a String in Python? xSicKxBot 0 1,306 10-04-2022, 11:37 AM
Last Post: xSicKxBot
  [Tut] Python Convert Image (JPG, PNG) to CSV xSicKxBot 0 1,298 09-10-2022, 12:05 PM
Last Post: xSicKxBot
  [Tut] Python Convert Parquet to CSV xSicKxBot 0 1,186 09-02-2022, 03:20 PM
Last Post: xSicKxBot
  [Tut] Python Convert Markdown Table to CSV xSicKxBot 0 1,226 09-01-2022, 01:21 AM
Last Post: xSicKxBot
  [Tut] How to Convert a Log to a CSV File in Python? xSicKxBot 0 1,292 08-30-2022, 02:11 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016