从Django

时间:2018-06-08 19:28:08

标签: python django csv web file-upload

我正在设计一个允许用户上传.xls文件的Web应用程序。上传时,应保存文件,转换为.csv文件,然后通过python导入脚本导入文件中包含的数据。

导入和转换数据的所有功能都在shell中完全正常运行,但是在通过localhost进行测试时,文件将转换为.csv并保存,但不会在新文件上运行任何脚本。

来自views.py的

    #for uploading data on the dashboard
    def file_upload(request):
        if request.method == 'POST':
            save_path = os.path.join(str(settings.MEDIA_ROOT), 'uploads', str(request.FILES['file']))
            try:
                validate_file_extension(request.FILES['file'])
                path = default_storage.save(save_path, request.FILES['file'])
                data = xls_to_csv(save_path, str(settings.MEDIA_ROOT))
                create_athlete(data, filename)
                create_phase(data)
                create_health_report(data)
                create_workout_report(data)
            except:
                return redirect('polar:dashboard')
            return redirect('polar:dashboard')
来自importscript.py的

    def xls_to_csv(file_name, save_path):
        #Formats into pandas dataframe.
        formatted_dataframe = pd.read_excel(file_name, index_col=None)
        #Converts the formatted into a csv file and save it.
        file_name = file_name.replace('.xls', '.csv')
        new_file = formatted_dataframe.to_csv(file_name))
        module_dir = os.path.dirname(settings.BASE_DIR)
        file_path = os.path.join(module_dir, 'uploads', file_name)
        sample_data = open(file_name, 'r')
        unfiltered_data = sample_data.readlines()
        data = unfiltered_data[1:]
        return data

就好像Django阻止打开和读取新创建的.csv文件一样。任何有关解决此问题的提示都将不胜感激!

1 个答案:

答案 0 :(得分:1)

如果在Linux或Mac环境中工作,请务必为上传目录提供读写权限。 或者如果是,那不是问题,那么看起来你在处理xls到CSV文件时遇到了问题,请看这个

import xlrd
import unicodecsv

def xls2csv (xls_filename, csv_filename):
    # Converts an Excel file to a CSV file.
    # If the excel file has multiple worksheets, only the first 
    #worksheet is converted.
    # Uses unicodecsv, so it will handle Unicode characters.
    # Uses a recent version of xlrd, so it should handle old .xls and 
   # new 
   #.xlsx equally well.

   wb = xlrd.open_workbook(xls_filename)
   sh = wb.sheet_by_index(0)

   fh = open(csv_filename,"wb")
   csv_out = unicodecsv.writer(fh, encoding='utf-8')

   for row_number in xrange (sh.nrows):
       csv_out.writerow(sh.row_values(row_number))

   fh.close()

取自here