Skip to content

Instantly share code, notes, and snippets.

@antun
Created July 25, 2014 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antun/b33cada78c06817a3720 to your computer and use it in GitHub Desktop.
Save antun/b33cada78c06817a3720 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import csv
import sys
import codecs
import pprint
from openpyxl import load_workbook
import cStringIO
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
pp = pprint.PrettyPrinter(indent=4)
parser = argparse.ArgumentParser()
parser.add_argument("input_file")
args = parser.parse_args()
if not ".xlsx" in args.input_file:
sys.stderr.write("Error: File does not have the ending \".xlsx\".\n")
sys.exit(2)
input_fh = open(args.input_file)
wb = load_workbook(filename = args.input_file)
ws = wb.active
csvFilename = args.input_file.replace(".xlsx", ".csv")
csvFile = open(csvFilename, "w")
csvFile.write(codecs.BOM_UTF8)
csvWriter = UnicodeWriter(csvFile)
for row in enumerate(ws.rows):
cells = []
rowNumber = row[0]
for col in enumerate(row[1]):
colNumber = col[0]
cell = col[1]
value = unicode(cell.value)
cells.append(value)
csvWriter.writerow(cells)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment