2015-01-27 1 views
0

xls와 csv를 구문 분석하기 위해 python의 xlrd와 csv를 사용하고 있습니다. 사용자가 xls 또는 xlsx 파일을 업로드하면 CSV를 구문 분석하고 생성 할 수 있습니다. 실제 파일을 생성하지만 대신 FileField 객체로 레코드를 생성하는 데 사용할 수있는 새로운 InMemoryUploadFile 객체를 업데이트하거나 생성하려고합니다. 그것을 할 방법이 있습니까? 대부분의 예제가 InMemoryUploadFile의 이미지 파일 용이지만 예제를 찾으려고했습니다. 여기 xls을 csv로 변환하고 InMemoryUploadedFile Django를 작성/업데이트하십시오.

샘플 코드는 내가 시도한다 -

import csv 
    import xlrd 
    import StringIO 
    from django.core.files.uploadedfile import InMemoryUploadedFile   
    ....... 
    ....... 

    #xls_file is excel file 
    file_name = '%s.csv'%(xls_file.name) 
    workbook = xlrd.open_workbook(file_contents=xls_file.read()) 
    all_worksheets = workbook.sheet_names() 

    # for now starting with reading the first sheet 
    worksheet_name = all_worksheets[0] 
    worksheet = workbook.sheet_by_name(worksheet_name) 

    csv_output = StringIO.StringIO() 
    csv_data = [] 
    for rownum in xrange(worksheet.nrows): 
     csv_data.append(
      [unicode(
       entry).encode("utf-8") for entry in worksheet.row_values(
       rownum)]) 
    writer = csv.writer(csv_output) 
    for row in csv_data: 
     writer.writerow(csv_data) 

    csv_file = InMemoryUploadedFile(writer, None, file_name, 'text/csv', 
           None, 'utf-8') 
    return csv_file 

답변

0

는 대신 ContentFile를 사용하려고 할 수 있습니까? Original tutorial

from django.core.files.base import ContentFile 
def save_file(csv_output): 
    mymodel = MyModel.objects.get(id=1) 
    file_content = ContentFile(csv_output.getvalue()) 
    mymodel.myfilefield.save(request.FILES['yourupload'].name, file_content)