Skip ke Konten
Menu
Pertanyaan ini telah diberikan tanda
3 Replies
11579 Tampilan

I have a wizard with a binary field where I upload a file and a method that opens it. 

excel_file_for_import = fields.Binary(string='import file')
file_name_for_import = fields.Char(string='file name')

@api.multi
def open_file(self):
    book = open_workbook(base64.decodestring(self.excel_file_for_import))
    ...

And the 1st line in the method throws an error:

TypeError: file() argument 1 must be encoded string without NULL bytes, not str

So what I'm doing wrong?

Avatar
Buang
Penulis Jawaban Terbai

Figured it out.

inputx = StringIO.StringIO()
inputx.write(base64.decodestring(self.excel_file_for_import))
book = open_workbook(file_contents=inputx.getvalue())




Avatar
Buang
Jawaban Terbai

hello

try like below code

import xlrd
import tempfile
import binascii 
def method_name(self):
        fp = tempfile.NamedTemporaryFile(suffix=".xlsx")
        fp.write(binascii.a2b_base64(self.xls_file)) # self.xls_file is your binary field
        fp.seek(0)

        workbook = xlrd.open_workbook(fp.name)
        sheet = workbook.sheet_by_index(0)

        for row_no in range(sheet.nrows):
            if row_no <= 0:
                fields = map(lambda row:row.value.encode('utf-8'), sheet.row(row_no))
            else:
                line = (map(lambda row:isinstance(row.value, unicode) and row.value.encode('utf-8') or str(row.value), sheet.row(row_no)))
                # in above line variable, you get the line by line value of excel file rows.
Avatar
Buang
Penulis

figured it out. used StringIO()

Post Terkait Replies Tampilan Aktivitas
1
Nov 18
6017
3
Jun 17
8907
4
Des 23
18219
2
Des 24
6722
2
Des 24
5796