|
| 1 | +# Copyright 2026 ACSONE SA/NV |
| 2 | +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). |
| 3 | + |
| 4 | +import io |
| 5 | + |
| 6 | +from odoo.exceptions import UserError |
| 7 | +from odoo.tools.misc import xlsxwriter |
| 8 | +from odoo.tools.translate import _ |
| 9 | + |
| 10 | +from odoo.addons.web.controllers.export import ExportFormat, ExportXlsxWriter |
| 11 | + |
| 12 | + |
| 13 | +class CleanedExportXlsxWriter(ExportXlsxWriter): |
| 14 | + def __init__(self, field_names, row_count=0, decimal_places=None): |
| 15 | + self.field_names = field_names |
| 16 | + self.output = io.BytesIO() |
| 17 | + self.workbook = xlsxwriter.Workbook(self.output, {"in_memory": True}) |
| 18 | + self.base_style = self.workbook.add_format({"text_wrap": True}) |
| 19 | + self.header_style = self.workbook.add_format({"bold": True}) |
| 20 | + self.header_bold_style = self.workbook.add_format( |
| 21 | + {"text_wrap": True, "bold": True, "bg_color": "#e9ecef"} |
| 22 | + ) |
| 23 | + self.date_style = self.workbook.add_format( |
| 24 | + {"text_wrap": True, "num_format": "yyyy-mm-dd"} |
| 25 | + ) |
| 26 | + self.datetime_style = self.workbook.add_format( |
| 27 | + {"text_wrap": True, "num_format": "yyyy-mm-dd hh:mm:ss"} |
| 28 | + ) |
| 29 | + self.worksheet = self.workbook.add_worksheet() |
| 30 | + self.value = False |
| 31 | + self.float_format = "#,##0.00" |
| 32 | + self.monetary_format = f'#,##0.{max(decimal_places or [2]) * "0"}' |
| 33 | + |
| 34 | + if row_count > self.worksheet.xls_rowmax: |
| 35 | + raise UserError( |
| 36 | + _( |
| 37 | + f"There are too many rows ({row_count} rows, limit:" |
| 38 | + f" {self.worksheet.xls_rowmax}) to export as Excel" |
| 39 | + f"2007-2013 (.xlsx) format. Consider splitting the export." |
| 40 | + ) |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +class ExcelExport(ExportFormat): |
| 45 | + def __init__(self, env): |
| 46 | + self.env = env |
| 47 | + |
| 48 | + @property |
| 49 | + def content_type(self): |
| 50 | + return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" |
| 51 | + |
| 52 | + @property |
| 53 | + def extension(self): |
| 54 | + return ".xlsx" |
| 55 | + |
| 56 | + def from_data(self, fields, rows): |
| 57 | + decimal_places = [ |
| 58 | + res["decimal_places"] |
| 59 | + for res in self.env["res.currency"].search_read([], ["decimal_places"]) |
| 60 | + ] |
| 61 | + with CleanedExportXlsxWriter(fields, len(rows), decimal_places) as xlsx_writer: |
| 62 | + for row_index, row in enumerate(rows): |
| 63 | + for cell_index, cell_value in enumerate(row): |
| 64 | + xlsx_writer.write_cell(row_index + 1, cell_index, cell_value) |
| 65 | + |
| 66 | + return xlsx_writer.value |
0 commit comments