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

[Image: 1f4a1.png] Challenge: Given a CSV file. How to convert it to an excel file in Python?

[Image: csv_to_excel-1024x576.jpg]

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

[Image: image-127.png]

All methods discussed in this tutorial show different code snippets to put into
Code:
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
Code:
.csv
to an
Code:
.xlsx
(Excel) in Python is to use the Pandas library.

  1. Install the
    Code:
    pandas
    library with
    Code:
    pip install pandas

  2. Install the
    Code:
    openpyxl
    library that is used internally by pandas with
    Code:
    pip install openpyxl

  3. Import the
    Code:
    pandas
    libray with
    Code:
    import pandas as pd

  4. Read the CSV file into a DataFrame
    Code:
    df
    by using the expression
    Code:
    df = pd.read_csv('my_file.csv')

  5. Store the DataFrame in an Excel file by calling
    Code:
    df.to_excel('my_file.xlsx', index=None, header=True)

Code:
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
Code:
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:

[Image: 1f30d.png] Tutorial: Pandas
Code:
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
    Code:
    csv
    module

  • Import the
    Code:
    openpyxl
    module

  • Read the CSV file into a list ofhttps://blog.finxter.com/python-list-of-lists/lists, one inner list per row, by using the
    Code:
    csv.reader()
    function

  • Write the list of lists to the Excel file by using the workbook representation of the
    Code:
    openpyxl
    library.

  • Get the active worksheet by calling
    Code:
    workbook.active

  • Write to the worksheet by calling
    Code:
    worksheet.append(row)
    and append one list of values, one value per cell.

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

Code:
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?

[Image: 1f680.png] 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!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: