Ejemplo n.º 1
0
def main():    
    if len(sys.argv) != 2:
        print "Use:\n\n\tpython ./convert.py file.xls"
        sys.exit()
    xls_file = sys.argv[1]
    
    if parameters.get('windows', True):
       end_of_line = "\r\n"
    else:   
       end_of_line = "\n"
       
    format = ""
    for f in parameters['field_trace']:
        format += f + parameters.get('column_separator', '')
    max_col = len(parameters['field_trace'])

    # Get file name and path:
    filename = os.path.join(parameters['path']['work'], xls_file)

    wb = xlrd.open_workbook(filename)
    sh = wb.sheet_by_index(0)

    csv_file = os.path.join(parameters['path']['worked'], parameters['file_csv'])
    print 'Creating CSV file: %s' % csv_file
    f_out = open(csv_file, 'wt')

    csv_field_len = 0
    for r in range(0, sh.nrows):    
        if r < parameters['start_row']:
            continue # jump N lines            
        format_row = [sh.cell_value(r, c) for c in range(0, max_col)]
        csv_row = format % tuple(format_row)
        if not csv_field_len: # save first row len (for test other)
            csv_field_len = len(csv_row)
            
        f_out.write(csv_row + end_of_line)
        print "%04d: %s%s" %(
           r,
           "# ERR lun. %s [OK: %s]" % (len(csv_row), csv_field_len) if len(csv_row) != csv_field_len else "",
           csv_row,
        )
    f_out.close()

    print "\nTRACE:", "*" * 60
    print "\nLunghezza riga:", csv_field_len, " + extra char: ", len(end_of_line), "Total:", csv_field_len + len(end_of_line)
    print "\nTracciato record:\n\n", format.replace ("%", "  ").replace("f", "\t(float)\n").replace("s", "\t(string)\n").replace("d", "\t(decimal)\n")
    print "\nFile letto:", filename
    print "File create:", csv_file
    print "\n"
Ejemplo n.º 2
0
def main():    
    # -------------------------------------------------------------------------
    #                  Open csv file for output the pricelist
    # -------------------------------------------------------------------------
    # Counter:
    total_xls = {}
    
    csv_file = os.path.join(parameters['path']['csv'], parameters['file_csv'])
    err_file = os.path.join(parameters['path']['csv'], parameters['file_err'])

    print "[INFO] Start conversion:"
    print '[INFO] Creating CSV file: %s and ERR: %s' % (csv_file, err_file)
    
    f_out = open(csv_file, 'wt')
    f_err = open(err_file, 'wt')

    format = "%-40s" # partner element
    for field in parameters['field_trace'].values():
        format += field + parameters.get('separator', '')

    if parameters.get('windows', True):
       format += "\r\n"
    else:   
       format += "\n"

    col_to_import = parameters['field_trace'].keys()

    # -------------------------------------------------------------------------
    #                     Loop on all XLS and XLSX files
    # -------------------------------------------------------------------------
    for xls_file in os.listdir(parameters['path']['xls']):
        if xls_file not in total_xls:
            total_xls[xls_file] = [0, 0] # import, error
        extension = xls_file.split(".")[-1].lower()        
        if extension not in ("xlsx", "xls"):
            continue # jump file
         
        # Get file name and path:
        filename = os.path.expanduser(os.path.join(parameters['path']['xls'], xls_file))
        print "[INFO] Export: %s" % filename

        try:
            wb = xlrd.open_workbook(filename)
        except:
            print "[ERROR] Impossibile leggere il file", filename
            continue

        sh = wb.sheet_by_index(0)
        for r in range(0, sh.nrows):
            if r == 0:        
                partner = sh.cell_value(r, 0)  # first col > partner code
                continue
            elif r == 1:                       # jump header and start test first col
                continue #started = True

            try:
                if sh.cell_value(r, 0):
                    total_xls[xls_file][0] += 1
                    format_row = [partner, ] + [float(sh.cell_value(r, c) or '0.0') if c in parameters['float_cols'] else sh.cell_value(r, c) for c in col_to_import]
                    f_out.write(format % tuple(format_row))
            except:
                total_xls[xls_file][1] += 1
                f_err.write("%-40s-Riga:%-10s[%-150s] #%s\r\n" % (partner, r, format_row, sys.exc_info()))
                #print "[ERR] %s) Error exporting line: %s" % (r, sys.exc_info())
    f_out.close()
    print "[INFO] %s" % (total_xls)
    print "[INFO] %s " % (format.replace("%", "[").replace("s", "]").replace("f", "]"))    
    print "[INFO] End conversion"