Skip to content

Instantly share code, notes, and snippets.

@niftycode
Created June 4, 2020 08:16
Show Gist options
  • Save niftycode/187c9855653ef819b810d186a3cb8a38 to your computer and use it in GitHub Desktop.
Save niftycode/187c9855653ef819b810d186a3cb8a38 to your computer and use it in GitHub Desktop.
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: https://opendata.schleswig-holstein.de/dataset/guterumschlag-im-kieler-hafen
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)
print(header_row)
# Index jeden Spaltenkopfes ausgeben
for index, column_header in enumerate(header_row):
print(index, column_header)
years, export_values = [], []
for row in reader:
years.append(row[4])
value = int(row[6])
export_values.append(value)
print(years)
print(export_values)
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 = workbook.active
# 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)
workbook.save('Kieler-Hafen-Export.xlsx')
export_data = read_csv_data()
write_excel_data(export_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment