openpyxl python - writing csv to excel gives 'number formatted as text'

前端 未结 2 745
旧时难觅i
旧时难觅i 2020-12-09 13:31

I have written a code to import a .csv file (containing numbers) into an excel file through openpyxl. It works, however, all the cells have written the numbers to the excel

2条回答
  •  爱一瞬间的悲伤
    2020-12-09 13:47

    This is the first google result, and I spent more time than I would like to admit working on this. I hope it helps someone in the future.

    def csvtoxlsx(csv_name, xlsx_name, directory, floats):
        """
        A function to convert a CSV file to XLSX so it can be used by openpyxl.
        csvname = file name of csv you want to convert (include .csv)
        xlsx_name = name you want to name the xlsx file (include .xlsx)
        cwd = directory to find csv file (can pass os.getcwd())
        floats = A list of column indexes in which floats appear
        """
    
        os.chdir(directory)
    
        f = open(csv_name, 'rt')
        csv.register_dialect('commas', delimiter=',')
        reader = csv.reader(f, dialect='commas')
        wb = Workbook()
        dest_filename = xlsx_name
        ws = wb.worksheets[0]
        ws.title = xlsx_name[:-5]
    
        for row_index, row in enumerate(reader):
            for column_index, cell in enumerate(row):
    
                column_letter = get_column_letter((column_index + 1))
    
                if column_index in floats:
                    s = cell
                    #Handles heading row or non floats
                    try:
                        s = float(s)
                        ws[('%s%s'%(column_letter, (row_index + 1)))].value = s
    
                    except ValueError:
                        ws[('%s%s'%(column_letter, (row_index + 1)))].value = s
    
                elif column_index not in floats:
                    #Handles openpyxl 'illigal chars'
                    try:
                        ws[('%s%s'%(column_letter, (row_index + 1)))].value = cell
    
                    except:
                        ws[('%s%s'%(column_letter, (row_index + 1)))].value = 'illigal char'
    
    
    
        wb.save(filename = dest_filename)
    

提交回复
热议问题