0

I have written a python code to store data in csv format but now need to store in .xlsx file. how to convert the below code and write the output in .xlsx file.

  details_file = self.get_local_storage_path() + '/Myfile.xlsx'
  csv_columns = (
        'id', 'name', 'place', 'salary', 'email',
          )

   with open(details_file, 'w') as csvfile:
            writer = csv.DictWriter(
                csvfile, fieldnames=csv_columns, extrasaction='ignore')
            writer.writeheader()
            for data in details:
                writer.writerow(data)
                
                
                
                

#I tried as below but getting error as TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'

with open(details_file, 'w') as csvfile:           
            print("inside open")
            workbook = xlsxwriter.Workbook(csvfile)
            worksheet = workbook.add_worksheet()
            print("before for loop")
            for data in details:
                worksheet.write(data)
            workbook.close()

1 Answer 1

2

I would use pandas for this:

import pandas as pd

# create the dataframe
df = pd.DataFrame(dict(zip(csv_columns, details)))

# save to csv:
df.to_csv(path, index=False)

#save to xlsx:
df.to_excel(path, index=False)

You might need to install openpyxl for the last line to work.

But if you really need to use xlsxwriter for this, here's how I would do it based on their tutorial:

import xlsxwriter

csv_columns = (
    'id', 'name', 'place', 'salary', 'email',
)
details = [
    [1, 'A', 'B', 2, '[email protected]'],
    [3, 'C', 'D', 4, '[email protected]'],
]

workbook = xlsxwriter.Workbook(path)
worksheet = workbook.add_worksheet()

for col, name in enumerate(csv_columns):
    worksheet.write(0, col, name)

for row, det in enumerate(details, 1):
    for col, value in enumerate(det):
        worksheet.write(row, col, value)

workbook.close()
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, but without pandas, I need to try
any help without pandas?
@Mia I updated the answer with an example using xlsxwriter
@Maz, Thanks but the output is like all rows and columns filled with csv_columns only not details. Any idea on how to solve this ? please
@Mia did you try to copy-paste and run my code to see if works?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.