简体   繁体   中英

Why an .xls file created with python csv and StringIO could be corrupted or unsafe?

I have a react component that makes an ajax call (with axios) to my little api and then I get the data response in an ".xls" file that is downloaded automatically. All works fine, but when I open the .xls file, Excel warns me with the following message:

File format and extension of 'myfile.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?

If I ignore this warn and I continue opening the file, it is opened and show's me the data that I expected correctly. But it is not very elegant to see this message for the user, how can I remove it?

My code is the next:
The code that creates the xml:

from io import StringIO  
import csv

MyAPIClass(Resource):
 (...)
    si = StringIO()
    cw = csv.writer(si, dialect='excel-tab')
    cw.writerows(dataset) #my iterable data list# 
    output = make_response(si.getvalue())
    output.headers["Content-Type"] = "application/vnd.ms-excel"
    output.headers["Content-Disposition"] = "attachment; filename=installations.xls"
    return output

The code to handle the axios (ajax) call to download the file created by my api:

exportToExcel() {
const FileDownload = require('react-file-download');
axios({method:'post', url: '/myapi_to_excel', headers: {'Accept': ' text/csv'})
        .then(res => {
            FileDownload(res.data, 'myfile.xls');
        });
}

Thank you!!! Have a nice day!

it's because .xls is a very old extension of excel. This extension is for 97-2003. If you change your script to create a .xlsx file afterwards everything should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM