📜  python openpyxl csv to excel - Python (1)

📅  最后修改于: 2023-12-03 14:46:01.682000             🧑  作者: Mango

Python openpyxl - CSV to Excel

Introduction

In this guide, I will introduce you to the openpyxl library in Python, which can be used to convert CSV (Comma-Separated Values) files to Excel format. The openpyxl library provides an easy and efficient way to read, write, and manipulate Excel files in Python.

Installation

Before you start, make sure you have openpyxl library installed. You can install it using the following command:

pip install openpyxl
Converting CSV to Excel

To convert a CSV file to Excel using openpyxl, you can follow the steps below:

  1. Import the required modules:
import csv
from openpyxl import Workbook
  1. Read the CSV file and store the data in a list or dictionary:
data = []
with open('input.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        data.append(row)
  1. Create an Excel workbook and select the active sheet:
wb = Workbook()
sheet = wb.active
  1. Write the data from the CSV file to the Excel sheet:
for row in data:
    sheet.append(row)
  1. Save the workbook as an Excel file:
wb.save('output.xlsx')
Example

Let's consider an example where we have a CSV file input.csv with the following data:

Name, Age, City
John, 25, New York
Alice, 30, London

We can use the code snippet mentioned above to convert this CSV file to an Excel file called output.xlsx.

import csv
from openpyxl import Workbook

data = []
with open('input.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        data.append(row)

wb = Workbook()
sheet = wb.active

for row in data:
    sheet.append(row)

wb.save('output.xlsx')

This code will convert the CSV file to an Excel file and save it as output.xlsx.

Conclusion

In this guide, we explored how to convert CSV files to Excel format using the openpyxl library in Python. You can use this library to perform various operations on Excel files, such as reading, writing, formatting, and more.