Snippets

Qi Peng 使用xlsxwriter将CSV文件转换为XLSX格式脚本

Created by Qi Peng
# coding: utf-8
# csv2xlsx.py
# 使用xlsxwriter将CSV文件转换为XLSX格式

import sys
import os
import csv
import xlsxwriter


def convert(csv_file, encoding='utf-8'):
    """将CSV文件转换为XLSX格式
       csv_file - 要转换的CSV文件路径
       encoding - 文件的字符编码
    """
    if os.path.exists(csv_file):
        # 输出文件路径
        xlsx_file = csv_file[:-4] + '.xlsx'
        print 'Convertting "{}" (encoding is "{}") into "{}"...'.format(csv_file, encoding, xlsx_file)
        
        workbook = xlsxwriter.Workbook(xlsx_file)
        worksheet = workbook.add_worksheet()
        
        # 遍历CSV文件
        row_num = 0
        for r in csv.reader(open(csv_file, 'rb')):
            col_num = 0
            for c in r:
                worksheet.write(row_num, col_num, c.decode(encoding))
                col_num += 1
            row_num += 1
            print 'Have processed {} rows.'.format(row_num)
            
        workbook.close()
        print '"{}" is ready.'.format(xlsx_file)
    else:
        print 'CSV file "{}" does not exist.'.format(csv_file)
    
    
if __name__ == '__main__':
    try:
        csv_file = sys.argv[1]
    except IndexError:
        print 'Usage: python csv2xlsx.py path-of-csv-file  file-encoding(default is utf-8)'
    else:
        try:
            encoding = sys.argv[2]
        except IndexError:
            encoding = 'utf-8'
        convert(csv_file=csv_file, encoding=encoding)

Comments (0)