Search code examples
pythoncsvopenpyxlxlsx

I can not realize the task of transferring from xlsx to csv


Condition:

In the Excel office program (or its analogues), you can always save the table in csv format.

Imagine that this functionality is broken. Write your own excel -> csv transcoder using the appropriate libraries. Your program should open the data.xlsx file containing arbitrary data and save the result in output.csv

Input format Not

Output format In the output.csv file, output data from the source file in csv format. Separator - "semicolon" Quotation - quotation marks

Notes Use the csv module

My code:

import csv
import openpyxl
from openpyxl import Workbook

wb = openpyxl.load_workbook(filename='data.xlsx', data_only=True)
with open('output.csv', 'w', newline='', encoding="utf8") as csvfile:
    writer = csv.writer(csvfile, delimiter=';', quotechar='"')
    for ws in wb:
        for row in ws.iter_rows():
            line = []
            for v in row:
                line.append(str(v.value))
            writer.writerow(line)

for some reason real numbers do not pass

enter image description here


Solution

  • Is it okay if I could suggest you to use pandas?

    import pandas as pd
    
    
    full_dataset = pd.read_xls('file.xlsx')
    

    Assuming that it has 2 worksheets

    full_dataset['worksheet1'].to_csv('worksheet1.csv', index = False, headers = True)
    full_dataset['worksheet2'].to_csv('worksheet2.csv', index = False, headers = True)
    

    And you are done. Have a nice day!