4

I have a django server which allow user to upload xlsx files, I want to access the data in it.

I know about openpyxl, however, it looks like it doesn't have a way to parse opened files, I do not want to save the file on disk and read it again.

How can I do it?

dspjm
  • 5,473
  • 6
  • 41
  • 62

2 Answers2

9

Actually, it's simpler than above:

    from openpyxl import load_workbook
    ...
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            wb = load_workbook(filename=request.FILES['file'].file)

The file attribute of FILES['file'] already returns a BytesIO instance ;)

Ricardo
  • 618
  • 9
  • 11
6

Read it as bytestream. This explanation helped me for the same task My solution:

    from openpyxl import load_workbook
    from io import BytesIO
    ...
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            file_in_memory = request.FILES['file'].read()
            wb = load_workbook(filename=BytesIO(file_in_memory))
Community
  • 1
  • 1
vz-ua
  • 61
  • 1
  • 4