Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Read a CSV file and save the data as Excel file
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
Cargo Handling (Port of Kiel, Germany)
For more information see:
Version: 1.0
Python 3.7+
Date created: 03.06.2020
import csv
import openpyxl
from openpyxl.styles import Font
DATA = 'kiel_gueterumschlag.csv'
def read_csv_data():
with open(DATA) as csv_file:
reader = csv.reader(csv_file, delimiter=';')
header_row = next(reader)
# Show header (1st row)
# Index jeden Spaltenkopfes ausgeben
for index, column_header in enumerate(header_row):
print(index, column_header)
years, export_values = [], []
for row in reader:
value = int(row[6])
return (years, export_values)
def write_excel_data(data):
# Call openpyxl.Workbook() to create a new blank Excel workbook
workbook = openpyxl.Workbook()
# Activate a sheet
sheet =
# Set a title
sheet.title = 'Güterumschlag im Kieler Hafen'
# Set headline style
bold16font = Font(size=16, bold=True)
sheet['A1'] = 'Jahr'
sheet['A1'].font = bold16font
sheet['B1'] = 'Ausfuhr (in to)'
sheet['B1'].font = bold16font
print(data[0]) # -> print years
print(data[1]) # -> print export values
years_row = 2
# Write years to 1st column
for year in data[0]:
sheet.cell(row=years_row, column=1).value = int(year)
years_row += 1
export_row = 2
# Write data to 2nd column
for export in data[1]:
sheet.cell(row=export_row, column=2).value = export
export_row += 1
# Save the workbook (excel file)'Kieler-Hafen-Export.xlsx')
export_data = read_csv_data()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.