简体   繁体   English

在Python CSV到XLS转换期间修改的格式

[英]Format modified during Python csv to xls conversion

My goal is to convert csv files localted in a directory to xls files. 我的目标是将本地目录中的csv文件转换为xls文件。

My csv files are notably composed of a row "mark" (eg 1.0000, 2.0000 ...) and a row "date" (eg 26/04/2013). 我的csv文件主要由“ mark”行(例如1.0000,2.0000 ...)和“ date”行(例如26/04/2013)组成。 The format of these two rows are very important for me. 这两行的格式对我来说非常重要。

I use the following code : 我使用以下代码:

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"

That code works pretty well and I have my new excel files. 该代码运行良好,并且我有新的Excel文件。

The problem is that my rows have been modified during that conversion. 问题是在转换期间我的行已被修改。 For example the content of the row "mark" is 1 instead of 1.00000. 例如,行“ mark”的内容是1而不是1.00000。 Moreover, the content of the row "date" is 2013/04/26 instead of 26/04/2013. 此外,“日期”行的内容是2013/04/26而不是2013/04/04。

Do you know what could I do, in order to keep the initial format rows of my csv files ? 您知道如何做才能保留csv文件的初始格式行吗?

Thank you very much. 非常感谢你。

You could define styles for the dates and numbers and then use a conditional to apply the style. 您可以为日期和数字定义样式,然后使用条件来应用样式。 Something like: 就像是:

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)

Sorry if it's not quite right, I'm running out the door as I write it up. 抱歉,如果写的不对,我快要关门了。 But hopefully it gets you in the right direction. 但希望它能使您朝正确的方向发展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM