📅  最后修改于: 2023-12-03 14:46:01.682000             🧑  作者: Mango
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.
Before you start, make sure you have openpyxl
library installed. You can install it using the following command:
pip install openpyxl
To convert a CSV file to Excel using openpyxl
, you can follow the steps below:
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')
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
.
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.