[ python ] Converting MS-EXCEL file into CSV file.
The module file can be downloaded here. ( Right click and select "save ..." )
# -*- coding: utf-8 -*-
# Python 2.4 or later required
import sys, csv
import pyExcelerator
# About csv module, see "http://www.python.org/doc/2.4/lib/module-csv.html"
# pyExcelerator can be redistributed with BSD Lisence and all rights reserved Roman V. Kiseliov
# The project page of pyExcelerator is "http://sourceforge.net/projects/pyexcelerator/"
def xls_to_csv( xls_file, csv_file ):
"""
xls_to_csv( excel_file, csv_file ):
convert MS-EXCEL file to CSV file.
Note, arguments xls_file and csv_file are filename, not file object.
Perhapse if the target EXCEL file includes the cell which value is dynamically generated by VBA, converting will be faild.
"""
xls_sheets = pyExcelerator.parse_xls( xls_file )
for sheet_id in len( xls_sheets ):
cell_dict = xls_sheets[sheet_id][1]
# set limitter row_max and column_max
for which in (0, 1):
exec "%s = max( [cell_dict.keys()[ key_index ][ which ] for key_index in xrange( len( cell_dict.keys() ) )] )" % ["row_max", "column_max"][which]
# creating csv file.
create_csv = csv.DictWriter( file( csv_file, "ab" ), fieldnames=range( column_max + 1 ) )
for row in xrange( row_max + 1 ):
create_csv.writerow( dict( enumerate( [cell_dict.copy().get( (row, column), '' ) for column in xrange( column_max + 1 )] ) ) )
# fileclosing depends on garbage collection.
if __name__ == "__main__":
if (sys.argv[1] in ("-h", "/h", "-?", "/?", "--help")) or ( len( sys.argv ) < 3 ):
print "Usage: python xls_to_csv.py ExcelFile CSVFile"
xls_to_csv( sys.argv[1], sys.argv[2] )
コメントにも書いてありますが、VBA はたぶん上手く変換できません。
バグなどのご報告は weisszwerg@gmail.com までお願いします。
| 固定リンク
この記事へのコメントは終了しました。
コメント