Last active
December 10, 2015 00:39
-
-
Save kfr2/4352954 to your computer and use it in GitHub Desktop.
Converts the specified CSV file to XLS using xlwt and outputs to stdout.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Converts the specified CSV file to XLS using xlwt. | |
Copyright 2012 Kevin Richardson | |
Permission is hereby granted, free of charge, to any person obtaining | |
a copy of this software and associated documentation files (the | |
"Software"), to deal in the Software without restriction, including | |
without limitation the rights to use, copy, modify, merge, publish, | |
distribute, sublicense, and/or sell copies of the Software, and to | |
permit persons to whom the Software is furnished to do so, subject to | |
the following conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE | |
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | |
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | |
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE | |
""" | |
import csv | |
import re | |
import sys | |
import xlwt | |
def csv_to_xls(csv_filename, output=None): | |
if output is None: | |
output = sys.stdout | |
int_re = re.compile(r'^\d+$') | |
float_re = re.compile(r'^\d+\.\d+$') | |
date_re = re.compile(r'^\d+-\d+-\d+$') | |
style = xlwt.XFStyle() | |
with open(csv_filename, 'rb') as csv_file: | |
workbook = xlwt.Workbook() | |
sheet = workbook.add_sheet('one') | |
reader = csv.reader(csv_file) | |
row_num = 0 | |
for row in reader: | |
column_num = 0 | |
for item in row: | |
format = 'general' | |
if re.match(date_re, item): | |
format = 'M/D/YY' | |
elif re.match(float_re, item): | |
item = float(item) | |
format = '0.00' | |
elif re.match(int_re, item): | |
item = float(item) | |
format = '0' | |
style.num_format_str = format | |
sheet.write(row_num, column_num, item, style) | |
column_num += 1 | |
row_num += 1 | |
workbook.save(output) | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
print 'Usage: csv2xls.py input.csv [output.xls]' | |
sys.exit(0) | |
output = None | |
if len(sys.argv) == 3: | |
output = sys.argv[2] | |
csv_to_xls(sys.argv[1], output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment