openpyxl convert CSV to EXCEL

后端 未结 3 1144
清酒与你
清酒与你 2020-12-14 12:54

How can I convert a CSV file with : delimiter to XLS (Excel sheet) using openpyxl module?

相关标签:
3条回答
  • 2020-12-14 13:37

    A much simpler, minimalist solution:

    import csv
    import openpyxl
    
    wb = openpyxl.Workbook()
    ws = wb.active
    
    with open('file.csv') as f:
        reader = csv.reader(f, delimiter=':')
        for row in reader:
            ws.append(row)
    
    wb.save('file.xlsx')
    
    0 讨论(0)
  • 2020-12-14 13:52

    Here is Adam's solution expanded to strip out characters that openpyxl considers illegal and will throw an exception for:

    import re
    from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
    ...
    ##ws.append(row) - Replace with the code below
    for i in row:
        ws.append([ILLEGAL_CHARACTERS_RE.sub('',i)])
    

    ILLEGAL_CHARACTERS_RE is a compiled regular expression containing the characters openpyxl deems "illegal". The code is simply substituting those characters with an empty string.

    Source: Bitbucket openpyxl issue #873 - Remove illegal characters instead of throwing an exception

    0 讨论(0)
  • 2020-12-14 13:55

    Well here you go...

    import csv
    from openpyxl import Workbook
    from openpyxl.cell import get_column_letter
    
    f = open(r'C:\Users\Asus\Desktop\herp.csv')
    
    csv.register_dialect('colons', delimiter=':')
    
    reader = csv.reader(f, dialect='colons')
    
    wb = Workbook()
    dest_filename = r"C:\Users\Asus\Desktop\herp.xlsx"
    
    ws = wb.worksheets[0]
    ws.title = "A Snazzy Title"
    
    for row_index, row in enumerate(reader):
        for column_index, cell in enumerate(row):
            column_letter = get_column_letter((column_index + 1))
            ws.cell('%s%s'%(column_letter, (row_index + 1))).value = cell
    
    wb.save(filename = dest_filename)
    
    0 讨论(0)
提交回复
热议问题