I am trying to write the output into xslx file, but able to only write the headers not able to write the data below headers.
import xlsxwriter
csv_columns = (
'id', 'name', 'place', 'salary', 'email',
)
details = [{'id':1, 'name': 'A', 'place':'B', 'salary': 2, 'email': '[email protected]'},
{'id':3, 'name':'C', 'place':'D', 'salary': 4, 'email':'[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()
This code is only writing the csv_columns in xslx file and repeating same in all rows as below
id name place salary email
id name place salary email
id name place salary email
How to solve this issue of repeating columns in xslx? any help ?
I expected like below:
id name place salary email
1 A B 2 [email protected]
3 C D 4 [email protected]
CodePudding user response:
I corrected your code. Now it works as you would expect:
import xlsxwriter
csv_columns = (
'id', 'name', 'place', 'salary', 'email',
)
values = [(1, 'A', 'B', 2, '[email protected]'),
(3, 'C', 'D', 4, '[email protected]')]
workbook = xlsxwriter.Workbook(path)
worksheet = workbook.add_worksheet()
row, col = 0, 0
worksheet.write_row(row, col, csv_columns)
row = 1
for value in values:
worksheet.write_row(row, col, value)
row = 1
workbook.close()
CodePudding user response:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
csv_columns = (
'id', 'name', 'place', 'salary', 'email',
)
details = [{'id':1, 'name': 'A', 'place':'B', 'salary': 2, 'email': '[email protected]'},
{'id':3, 'name':'C', 'place':'D', 'salary': 4, 'email':'[email protected]'}]
details_values = [tuple(d.values()) for d in details]
details_values.insert(0, csv_columns)
for row in details_values:
print(row)
ws.append(row)
wb.save(output_file_path)