Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
1 Trả lời
4649 Lượt xem

Hi, i'm using odoo 13.
I want to import an XLSX file, extract data from it and based on this data associate other data with other fields.


playlist.py:

from typing import Tuple
from xlrd import open_workbook
from odoo import api, fields, models, _, exceptions
class Playlist(models.Model):
xls_file = fields.Binary("File")
song_ids = fields.Many2many('music.song', 'music_playlist_song_rel', 'playlist_id', 'song_id',
string='Songs, ondelete='cascade')

def extract_songs_from_xlsx(self) -> Tuple[list, dict]:
workbook = open_workbook(file_contents=self.xls_file)
sheet = workbook.active
songs = {}
for row in sheet.iter_rows(min_row=2, values_only=True):
song_name = row[0]
song_artist = row[1]
songs.update({song_name: song_artist})

songs.pop(list(songs.keys())[-1]) # remove credit

matched_songs = []
for song_name, artist_name in songs.items():
matched_songs_names = self.env['music.song'].search(
[('name', '=', song_name)])

for song in matched_songs_names:
for artist in song.artist_ids:
if artist_name in artist:
matched_songs.append(song)
break

return matched_songs, {"searched_songs": len(sheet.iter_rows(min_row=2, values_only=True)) - 1,
"matched_songs": len(matched_songs)}


@api.onchange('xls_file')
def insert_songs(self):
if self.xls_file:
results = self.extract_songs_from_xlsx()
self.song_ids = results[0]
return {
'warning': {
'title': 'Warning',
'message': f'Found {results[1]["matched_songs"]} songs out of {results[1]["searched_songs"]} searched',
}}

playlist.xml:

field name="xls_file"/>f
field name="song_ids"/>


error:

  File "/usr/lib/python3/dist-packages/xlrd/book.py", line 1265, in bof_error
    raise XLRDError('Unsupported format, or corrupt file: ' + msg)
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'UEsDBBQA'
Has anyone encountered this problem before and knows how to solve it?



Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

Your file is still in base64. You need to:

from base64 import b64decode

book = xlrd.open_workbook(file_contents=b64decode(self.file) or b'')


Ảnh đại diện
Huỷ bỏ
Bài viết liên quan Trả lời Lượt xem Hoạt động
1
thg 10 20
4524
2
thg 3 15
3502
2
thg 12 23
1755
4
thg 10 23
4358
3
thg 3 21
3044