wharton / drf-excel

An XLSX spreadsheet renderer for Django REST Framework.
BSD 3-Clause "New" or "Revised" License
212 stars 40 forks source link

On the scope of your package utitilies... #85

Closed couzhei closed 1 month ago

couzhei commented 1 month ago

I'm sorry if this might be considered as an inappropriate issue. I am currently working on developing an excel generation into my django projects, for forms such as these: DTInspecton (Before).xlsx Although I briefly read your README.md, I am still wondering if I could be able to use your package for filling or generating forms like above taking data as a JSON format and then filling the cells in accordance. Is that possible? What I get is that your package treats excel files as mere tabular datasets and place its focus entirely in that area, or did I misinterpret it? Thanks in advance.

FlipperPA commented 1 month ago

@couzhei drf-excel is for use with RESTful API endpoints. It sounds like your use case is a bit more straightforward than that. Here's an example of how you might take JSON data and write it to spreadsheets without the complexity of RESTful APIs in the middle.

import json
from openpyxl import Workbook

# Sample JSON data (as a string, but could be read from a file)
json_data = '''
{
    "employees": [
        {"name": "Adrian", "age": 25, "department": "Music"},
        {"name": "Jacob", "age": 26, "department": "Data"},
        {"name": "Simon", "age": 27, "department": "IT"}
    ]
}
'''

# Load the JSON data into a Python dictionary
data = json.loads(json_data)

# Create a new Excel workbook and select the active worksheet
wb = Workbook()
ws = wb.active
ws.title = "Employees"

# Write the header row (keys from the first dictionary in the list)
headers = data['employees'][0].keys()
ws.append(list(headers))

# Write the data rows
for employee in data['employees']:
    ws.append(list(employee.values()))

# Save the workbook to a file
wb.save("employees.xlsx")