Skip to main content
 首页 » 编程设计

python之在 Python csv 到 xls 转换期间修改的格式

2025年05月04日6xing901022

我的目标是将本地目录中的 csv 文件转换为 xls 文件。

我的 csv 文件特别由一行“标记”(例如 1.0000、2.0000 ...)和一行“日期”(例如 26/04/2013)组成。 这两行的格式对我来说非常重要。

我使用以下代码:

import sys, csv, xlwt, glob, os 
import shutil 
 
def cont_directory (): 
    return glob.glob('/home/julien/excel/csv/*.csv') 
liste = cont_directory() 
 
try:  
    for i in liste: 
        f=open(i, 'rb') 
        g = csv.reader ((f), delimiter = ";") 
        workbook=xlwt.Workbook() 
        sheet= xlwt.Workbook() 
 
 
        sheet = workbook.add_sheet("To be modified") 
 
        for rowi, row in enumerate(g): 
            for coli, value in enumerate(row): 
                sheet.write(rowi,coli,value) 
        workbook.save(i + ".xls") 
 
except:  
    print "epic_fail_Conversion", sys.exc_info() 
 
 
for i in glob.glob ('/home/julien/excel/csv/*.xls'): 
    shutil.copy2 (i, '/home/julien/excel/xls') 
 
try: 
    for j in glob.glob('/home/julien/excel/xls/*.xls'): 
        os.rename (j, j.replace ('.csv', '')) 
 
except:  
       print "epic_fail_Conversion", sys.exc_info() 
 
 
print "End" 

该代码运行良好,我有了新的 excel 文件。

问题是我的行在转换过程中被修改了。 例如,“mark”行的内容是 1 而不是 1.00000。 此外,“日期”行的内容是 2013/04/26 而不是 26/04/2013。

您知道我该怎么做才能保留我的 csv 文件的初始格式行吗?

非常感谢。

请您参考如下方法:

您可以为日期和数字定义样式,然后使用条件来应用样式。像这样的东西:

datestyle = xlwt.XFStyle() 
datestyle.num_format_str = 'D/M/YYYY'  
 
numstyle = xlwt.XFStyle() 
numstyle.num_format_str = '#,##0.0000' 
 
.... 
 
for rowi, row in enumerate(g): 
            for coli, value in enumerate(row): 
                if coli == 0:  #or wherever your date is, if it's in a fixed spot 
                    sheet.write(rowi,coli,value, datestyle) 
                elif coli == 1: #or wherever your number is 
                    sheet.write(rowi,coli,value, numstyle) 
                else: 
                    sheet.write(rowi,coli,value) 

抱歉,如果它不是很正确,我在写它的时候就跑出门了。但希望它能让您朝着正确的方向前进。