diff --git a/excel_import_export/README.rst b/excel_import_export/README.rst deleted file mode 100644 index bb2b29a1c..000000000 --- a/excel_import_export/README.rst +++ /dev/null @@ -1,202 +0,0 @@ -========================== -Excel Import/Export/Report -========================== - -.. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - !! This file is generated by oca-gen-addon-readme !! - !! changes will be overwritten. !! - !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - -.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png - :target: https://odoo-community.org/page/development-status - :alt: Beta -.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png - :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html - :alt: License: AGPL-3 -.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fserver--tools-lightgray.png?logo=github - :target: https://github.com/OCA/server-tools/tree/12.0/excel_import_export - :alt: OCA/server-tools -.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png - :target: https://translation.odoo-community.org/projects/server-tools-12-0/server-tools-12-0-excel_import_export - :alt: Translate me on Weblate -.. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png - :target: https://runbot.odoo-community.org/runbot/149/12.0 - :alt: Try me on Runbot - -|badge1| |badge2| |badge3| |badge4| |badge5| - -The module provide pre-built functions and wizards for developer to build excel import / export / report with ease. - -Without having to code to create excel file, developer do, - -- Create menu, action, wizard, model, view a normal Odoo development. -- Design excel template using standard Excel application, e.g., colors, fonts, formulas, etc. -- Instruct how the data will be located in Excel with simple dictionary instruction or from Odoo UI. -- Odoo will combine instruction with excel template, and result in final excel file. - -**Table of contents** - -.. contents:: - :local: - -Installation -============ - -To install this module, you need to install following python library, **xlrd, xlwt, openpyxl**. - -Then, simply install **excel_import_export**. - -For demo, install **excel_import_export_demo**. - -Usage -===== - -This module contain pre-defined function and wizards to make exporting, importing and reporting easy. - -At the heart of this module, there are 2 `main methods` - -- ``self.env['xlsx.export'].export_xlsx(...)`` -- ``self.env['xlsx.import'].import_xlsx(...)`` - -For reporting, also call `export_xlsx(...)` but through following method - -- ``self.env['xslx.report'].report_xlsx(...)`` - -After install this module, go to Settings > Excel Import/Export > XLSX Templates, this is where the key component located. - -As this module provide tools, it is best to explain as use cases. For example use cases, please install **excel_import_export_demo** - -**Use Case 1:** Export/Import Excel on existing document - -This add export/import action menus in existing document (example - excel_import_export_demo/import_export_sale_order) - -1. Create export action menu on document, with res_model="export.xlsx.wizard" and src_model="", and context['template_domain'] to locate the right template -- actions.xml -2. Create import action menu on document, with res_model="import.xlsx.wizard" and src_model="", and context['template_domain'] to locate the right template -- action.xml -3. Create/Design Excel Template File (.xlsx), in the template, name the underlining tab used for export/import -- .xlsx -4. Create instruction dictionary for export/import in xlsx.template model -- templates.xml - -**Use Case 2:** Import Excel Files - -With menu wizard to create new documents (example - excel_import_export_demo/import_sale_orders) - -1. Create report menu with search wizard, res_model="import.xlsx.wizard" and context['template_domain'] to locate the right template -- menu_action.xml -2. Create Excel Template File (.xlsx), in the template, name the underlining tab used for import -- .xlsx -3. Create instruction dictionary for import in xlsx.template model -- templates.xml - -**Use Case 3:** Create Excel Report - -This create report menu with criteria wizard. (example - excel_import_export_demo/report_sale_order) - -1. Create report's menu, action, and add context['template_domain'] to locate the right template for this report -- .xml -2. Create report's wizard for search criteria. The view inherits ``excel_import_export.xlsx_report_view`` and mode="primary". In this view, you only need to add criteria fields, the rest will reuse from interited view -- -3. Create report model as models.Transient, then define search criteria fields, and get reporing data into ``results`` field -- .py -4. Create/Design Excel Template File (.xlsx), in the template, name the underlining tab used for report results -- .xlsx -5. Create instruction dictionary for report in xlsx.template model -- templates.xml - -**Note:** - -Another option for reporting is to use report action (report_type='excel'), I.e., - -.. code-block:: xml - - - -By using report action, Odoo will find template using combination of model and name, then do the export for the underlining record. -Please see example in excel_import_export_demo/report_action, which shows, - -1. Print excel from an active sale.order -2. Run partner list report based on search criteria. - -Known issues / Roadmap -====================== - -- Module extension e.g., excel_import_export_async, that add ability to execute as async process. -- Ability to add contextual action in XLSX Tempalte, e.g., Add import action, Add export action. In similar manner as in Server Action. - -Changelog -========= - -12.0.1.0.5 (2019-12-19) -~~~~~~~~~~~~~~~~~~~~~~~ - -* Speed up export when dealing with many rows - -12.0.1.0.4 (2019-08-28) -~~~~~~~~~~~~~~~~~~~~~~~ - -* Fix style sum in footer - -12.0.1.0.3 (2019-08-09) -~~~~~~~~~~~~~~~~~~~~~~~ - -* Add report action for report_type = 'excel' - -12.0.1.0.2 (2019-08-07) -~~~~~~~~~~~~~~~~~~~~~~~ - -* Small fix, to ensure that system parameter 'path_temp_file' (ir.config_parameter) is readable - -12.0.1.0.1 (2019-06-24) -~~~~~~~~~~~~~~~~~~~~~~~ - -* Fix wizard on v12 can't download sample template file - https://github.com/OCA/server-tools/issues/1574 - -12.0.1.0.0 (2019-02-24) -~~~~~~~~~~~~~~~~~~~~~~~ - -* Start of the history - -Bug Tracker -=========== - -Bugs are tracked on `GitHub Issues `_. -In case of trouble, please check there if your issue has already been reported. -If you spotted it first, help us smashing it by providing a detailed and welcomed -`feedback `_. - -Do not contact contributors directly about support or help with technical issues. - -Credits -======= - -Authors -~~~~~~~ - -* Ecosoft - -Contributors -~~~~~~~~~~~~ - -* Kitti Upariphutthiphong. (http://ecosoft.co.th) -* Saran Lim. (http://ecosoft.co.th) - -Maintainers -~~~~~~~~~~~ - -This module is maintained by the OCA. - -.. image:: https://odoo-community.org/logo.png - :alt: Odoo Community Association - :target: https://odoo-community.org - -OCA, or the Odoo Community Association, is a nonprofit organization whose -mission is to support the collaborative development of Odoo features and -promote its widespread use. - -.. |maintainer-kittiu| image:: https://github.com/kittiu.png?size=40px - :target: https://github.com/kittiu - :alt: kittiu - -Current `maintainer `__: - -|maintainer-kittiu| - -This module is part of the `OCA/server-tools `_ project on GitHub. - -You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/excel_import_export/__manifest__.py b/excel_import_export/__manifest__.py index 212408875..7e52a8149 100644 --- a/excel_import_export/__manifest__.py +++ b/excel_import_export/__manifest__.py @@ -4,22 +4,23 @@ { "name": "Excel Import/Export/Report", "summary": "Base module for developing Excel import/export/report", - "version": "12.0.1.0.4", + "version": "13.0.1.0.0", "author": "Ecosoft,Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/server-tools/", "category": "Tools", "depends": ["mail"], - "external_dependencies": {"python": ["xlrd", "xlwt", "openpyxl",],}, + "external_dependencies": {"python": ["xlrd", "xlwt", "openpyxl"]}, "data": [ "security/ir.model.access.csv", "wizard/export_xlsx_wizard.xml", "wizard/import_xlsx_wizard.xml", + "wizard/report_xlsx_wizard.xml", "views/xlsx_template_view.xml", "views/xlsx_report.xml", "views/webclient_templates.xml", ], "installable": True, - "development_status": "beta", + "development_status": "Beta", "maintainers": ["kittiu"], } diff --git a/excel_import_export/i18n/excel_import_export.pot b/excel_import_export/i18n/excel_import_export.pot index d2843ba6e..f6d2eaf9f 100644 --- a/excel_import_export/i18n/excel_import_export.pot +++ b/excel_import_export/i18n/excel_import_export.pot @@ -193,18 +193,6 @@ msgstr "" msgid "Allow Choose Template" msgstr "" -#. module: excel_import_export -#: model:ir.model.fields,field_description:excel_import_export.field_export_xlsx_wizard__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_export__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_import__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_report__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_styles__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_template__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_template_export__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_template_import__attachment_ids -msgid "Attachments" -msgstr "" - #. module: excel_import_export #: model:ir.model,name:excel_import_export.model_xlsx_styles msgid "Available styles for excel" @@ -383,13 +371,7 @@ msgid "Error filling data into Excel sheets\n" msgstr "" #. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_import.py:212 -#, python-format -msgid "Error importing data" -msgstr "" - -#. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_import.py:224 +#: code:addons/excel_import_export/models/xlsx_import.py:219 #, python-format msgid "Error importing data\n" "%s" @@ -670,7 +652,7 @@ msgid "Invalid declaration, %s has no valid field type" msgstr "" #. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_import.py:222 +#: code:addons/excel_import_export/models/xlsx_import.py:217 #, python-format msgid "Invalid file style, only .xls or .xlsx file allowed" msgstr "" @@ -737,7 +719,7 @@ msgid "No Delete" msgstr "" #. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_import.py:254 +#: code:addons/excel_import_export/models/xlsx_import.py:249 #, python-format msgid "No data_dict['__IMPORT__'] in template %s" msgstr "" @@ -818,7 +800,7 @@ msgid "Post Import Hook" msgstr "" #. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_import.py:237 +#: code:addons/excel_import_export/models/xlsx_import.py:232 #, python-format msgid "Post import operation error\n" "%s" @@ -961,8 +943,8 @@ msgid "Template with CSV Quoting = False, data must not contain the same char as msgstr "" #. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_export.py:228 -#: code:addons/excel_import_export/models/xlsx_import.py:249 +#: code:addons/excel_import_export/models/xlsx_export.py:230 +#: code:addons/excel_import_export/models/xlsx_import.py:244 #, python-format msgid "Template's model mismatch" msgstr "" diff --git a/excel_import_export/i18n/zh_CN.po b/excel_import_export/i18n/zh_CN.po index 7fec0fdef..f8f0aa3fb 100644 --- a/excel_import_export/i18n/zh_CN.po +++ b/excel_import_export/i18n/zh_CN.po @@ -1,6 +1,6 @@ # Translation of Odoo Server. # This file contains the translation of the following modules: -# * excel_import_export +# * excel_import_export # msgid "" msgstr "" @@ -32,8 +32,7 @@ msgstr "'%s' 找不到工作表" #: model:ir.model.fields,help:excel_import_export.field_export_xlsx_wizard__state #: model:ir.model.fields,help:excel_import_export.field_import_xlsx_wizard__state #: model:ir.model.fields,help:excel_import_export.field_xlsx_report__state -msgid "" -"* Choose: wizard show in user selection mode\n" +msgid "* Choose: wizard show in user selection mode\n" "* Get: wizard show results from user action" msgstr "" "* 选择:用户选择模式下的向导显示\n" @@ -46,35 +45,24 @@ msgstr "单元格:Excel工作表中的数据位置(例如:A1,B1,... #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Continue: If not selected, start rolling with specified first row " -"cells. If selected, continue from previous one2many field" -msgstr "" -"继续: 如果未选中,则使用指定的第一行单元格开始滚动。 如果选中,则从之" -"前的one2many字段继续" +msgid "Continue: If not selected, start rolling with specified first row cells. If selected, continue from previous one2many field" +msgstr "继续: 如果未选中,则使用指定的第一行单元格开始滚动。 如果选中,则从之前的one2many字段继续" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Field Cond.: Python code in ${...} to manipulate field " -"value, e.g., if field = product_id, value will represent " -"product object, e.g., ${value and value.uom_id.name or \"\"}" +msgid "Field Cond.: Python code in ${...} to manipulate field value, e.g., if field = product_id, value will represent product object, e.g., ${value and value.uom_id.name or \"\"}" msgstr "" -"字段条件: Python代码${...} 操纵字段值, 例如, if field = " -"product_id, value 将代表产品对象, 例如, ${value and value." -"uom_id.name or \"\"}" +"字段条件: Python代码${...} 操纵字段值, 例如, if field = product_id, " +"value 将代表产品对象, 例如, ${value and value.uom_id.name or \"\"" +"}" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Field Cond.: Python code in ${...} value will represent " -"data from excel cell, e.g., if A1 = 'ABC', value will represent " -"'ABC', e.g., ${value == \"ABC\" and \"X\" or \"Y\"} thus can " -"change from cell value to other value for import." +msgid "Field Cond.: Python code in ${...} value will represent data from excel cell, e.g., if A1 = 'ABC', value will represent 'ABC', e.g., ${value == \"ABC\" and \"X\" or \"Y\"} thus can change from cell value to other value for import." msgstr "" -"字段条件: Python代码 ${...} 值将代表来自excel 单元格的数" -"据, 例如, if A1 = 'ABC', value 代表'ABC',例如, ${value == " -"\"ABC\" and \"X\" or \"Y\"} 因此可以从单元格值更改为其他值以进行导入." +"字段条件: Python代码 ${...} 值将代表来自excel 单元格的数据, 例如, if A1 = " +"'ABC', value 代表'ABC',例如, ${value == \"ABC\" and \"X\" or " +"\"Y\"} 因此可以从单元格值更改为其他值以进行导入." #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form @@ -83,18 +71,13 @@ msgstr "字段: 要导入的记录的字段,例如product_id" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Field: Field of the record, e.g., product_id.uom_id.name. They are " -"orm compliant." +msgid "Field: Field of the record, e.g., product_id.uom_id.name. They are orm compliant." msgstr "字段: 记录的字段,例如product_id.uom_id.name。他们是合规的。" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"No Delete: By default, all one2many lines will be deleted before " -"import. Select this, to avoid deletion" -msgstr "" -"不删除: 默认情况下,导入前将删除所有one2many行。选择此项,以避免删除" +msgid "No Delete: By default, all one2many lines will be deleted before import. Select this, to avoid deletion" +msgstr "不删除: 默认情况下,导入前将删除所有one2many行。选择此项,以避免删除" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form @@ -103,12 +86,8 @@ msgstr "备注:" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Row Field: Use _HEAD_ for the record itself, and one2many field (e." -"g., line_ids) for row data" -msgstr "" -"行字段: 使用_HEAD_表示记录本身,使用one2many字段(例如line_ids)表示行" -"数据" +msgid "Row Field: Use _HEAD_ for the record itself, and one2many field (e.g., line_ids) for row data" +msgstr "行字段: 使用_HEAD_表示记录本身,使用one2many字段(例如line_ids)表示行数据" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form @@ -117,34 +96,22 @@ msgstr "工作表: excel工作表的名称(例如,工作表1)或索 #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Sheet: Name (e.g., Sheet 1) or index (e.g., 1) of excel sheet to " -"export data to" -msgstr "" -"工作表: 要将数据导出到的Excel工作表的名称(例如,工作表1)或索引(例" -"如,1)" +msgid "Sheet: Name (e.g., Sheet 1) or index (e.g., 1) of excel sheet to export data to" +msgstr "工作表: 要将数据导出到的Excel工作表的名称(例如,工作表1)或索引(例如,1)" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Style w/Cond.: Conditional style by python code in #?...?, e.g., apply style for specific product, #?value.name == \"ABC\" " -"and #{font=bold;fill=red} or None?" +msgid "Style w/Cond.: Conditional style by python code in #?...?, e.g., apply style for specific product, #?value.name == \"ABC\" and #{font=bold;fill=red} or None?" msgstr "" -"样式条件: python代码中的条件样式 #?...?, 例如,为特定产品" -"应用样式, #?value.name == \"ABC\" and #{font=bold;fill=red} or None?" +"样式条件: python代码中的条件样式 #?...?, 例如,为特定产品应用样式, #" +"?value.name == \"ABC\" and #{font=bold;fill=red} or None?" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Style: Default style in #{...} that apply to each cell, " -"e.g., #{align=left;style=text}. See module's style.py " -"for available styles." +msgid "Style: Default style in #{...} that apply to each cell, e.g., #{align=left;style=text}. See module's style.py for available styles." msgstr "" "样式: 默认样式#{...} 适用于每个单元格, 例如, " -"#{align=left;style=text}. 请参阅模块的style.py 可用的样" -"式。" +"#{align=left;style=text}. 请参阅模块的style.py 可用的样式。" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form @@ -153,20 +120,16 @@ msgstr "总和: 在最后一行添加总和值, @{sum}" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"\n" +msgid "\n" "{\n" " '__EXPORT__': {\n" " 'sale_order': { # sheet can be name (string) or index (integer)\n" " '_HEAD_': {\n" -" 'B2': 'partner_id.display_name${value or \"\"}#{align=left;" -"style=text}',\n" +" 'B2': 'partner_id.display_name${value or \"\"}#{align=left;style=text}',\n" " 'B3': 'name${value or \"\"}#{align=left;style=text}',\n" " },\n" -" 'line_ids': { # prefix with _CONT_ to continue rows from " -"previous row field\n" -" 'A6': 'product_id.display_name${value or \"\"}" -"#{style=text}',\n" +" 'line_ids': { # prefix with _CONT_ to continue rows from previous row field\n" +" 'A6': 'product_id.display_name${value or \"\"}#{style=text}',\n" " 'C6': 'product_uom_qty${value or 0}#{style=number}',\n" " 'E6': 'price_unit${value or 0}#{style=number}',\n" " 'G6': 'price_subtotal${value or 0}#{style=number}',\n" @@ -175,8 +138,7 @@ msgid "" " },\n" " '__IMPORT__': {\n" " 'sale_order': { # sheet can be name (string) or index (integer)\n" -" 'order_line': { # prefix with _NODEL_ to not delete rows before " -"import\n" +" 'order_line': { # prefix with _NODEL_ to not delete rows before import\n" " 'A6': 'product_id',\n" " 'C6': 'product_uom_qty',\n" " 'E6': 'price_unit${value > 0 and value or 0}',\n" @@ -193,14 +155,14 @@ msgstr "" " '__EXPORT__': {\n" " 'sale_order': { # 工作表名称可以是(字符串)或索引(整数)\n" " '_HEAD_': {\n" -" 'B2': 'partner_id.display_name${value or \"\"}#{align=left;" -"style=text}',\n" +" 'B2': 'partner_id.display_name${value or \"\"" +"}#{align=left;style=text}',\n" " 'B3': 'name${value or \"\"}#{align=left;style=text}',\n" " },\n" " 'line_ids': { # prefix with _CONT_ to continue rows from " "previous row field\n" -" 'A6': 'product_id.display_name${value or \"\"}" -"#{style=text}',\n" +" 'A6': 'product_id.display_name${value or \"\"}#{style=text}'," +"\n" " 'C6': 'product_uom_qty${value or 0}#{style=number}',\n" " 'E6': 'price_unit${value or 0}#{style=number}',\n" " 'G6': 'price_subtotal${value or 0}#{style=number}',\n" @@ -234,8 +196,7 @@ msgstr "model: 活动模型,例如., self.env['my.model']" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"object: record object or line object depends on Row Field" +msgid "object: record object or line object depends on Row Field" msgstr "object: 记录对象或行对象依赖于 行字段" #. module: excel_import_export @@ -252,11 +213,8 @@ msgstr "value: 值来自 字段" #. openerp-web #: code:addons/excel_import_export/static/src/js/report/action_manager_report.js:49 #, python-format -msgid "" -"A popup window with your report was blocked. You may need to change your " -"browser settings to allow popup windows for this page." -msgstr "" -"您的报告的弹出窗口被阻止。您可能需要更改浏览器设置以允许此页面的弹出窗口。" +msgid "A popup window with your report was blocked. You may need to change your browser settings to allow popup windows for this page." +msgstr "您的报告的弹出窗口被阻止。您可能需要更改浏览器设置以允许此页面的弹出窗口。" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form @@ -283,18 +241,6 @@ msgstr "添加工作表部分" msgid "Allow Choose Template" msgstr "添加表单部分" -#. module: excel_import_export -#: model:ir.model.fields,field_description:excel_import_export.field_export_xlsx_wizard__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_export__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_import__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_report__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_styles__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_template__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_template_export__attachment_ids -#: model:ir.model.fields,field_description:excel_import_export.field_xlsx_template_import__attachment_ids -msgid "Attachments" -msgstr "" - #. module: excel_import_export #: model:ir.model,name:excel_import_export.model_xlsx_styles msgid "Available styles for excel" @@ -302,8 +248,7 @@ msgstr "excel的可用样式" #. module: excel_import_export #: model:ir.model.fields,help:excel_import_export.field_xlsx_template_import__no_delete -msgid "" -"By default, all rows will be deleted before import.\n" +msgid "By default, all rows will be deleted before import.\n" "Select No Delete, otherwise" msgstr "" "默认情况下,导入前将删除所有行。\n" @@ -326,8 +271,7 @@ msgstr "CSV引用" #. module: excel_import_export #: model:ir.model.fields,help:excel_import_export.field_xlsx_template__post_import_hook -msgid "" -"Call a function after successful import, i.e.,\n" +msgid "Call a function after successful import, i.e.,\n" "${object.post_import_do_something()}" msgstr "" "成功导入后调用函数,即,\n" @@ -347,7 +291,8 @@ msgid "Cell" msgstr "单元格" #. module: excel_import_export -#: selection:export.xlsx.wizard,state:0 selection:import.xlsx.wizard,state:0 +#: selection:export.xlsx.wizard,state:0 +#: selection:import.xlsx.wizard,state:0 #: selection:xlsx.report,state:0 msgid "Choose" msgstr "选择" @@ -466,8 +411,7 @@ msgstr "文件必须处于草稿状态" #. module: excel_import_export #: code:addons/excel_import_export/models/xlsx_import.py:89 #, python-format -msgid "" -"Error deleting data\n" +msgid "Error deleting data\n" "%s" msgstr "" "删除数据时出错\n" @@ -476,29 +420,16 @@ msgstr "" #. module: excel_import_export #: code:addons/excel_import_export/models/xlsx_export.py:141 #, python-format -msgid "" -"Error filling data into Excel sheets\n" +msgid "Error filling data into Excel sheets\n" "%s" msgstr "" "将数据填充到Excel工作表时出错\n" "%s" #. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_import.py:212 -#, fuzzy, python-format -#| msgid "" -#| "Error importing data\n" -#| "%s" -msgid "Error importing data" -msgstr "" -"导入数据时出错\n" -"%s" - -#. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_import.py:224 +#: code:addons/excel_import_export/models/xlsx_import.py:219 #, python-format -msgid "" -"Error importing data\n" +msgid "Error importing data\n" "%s" msgstr "" "导入数据时出错\n" @@ -553,25 +484,17 @@ msgstr "导出" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Export Instruction is how to write data from an active data record to " -"specified cells in excel sheet.\n" -" For example, an active record can be a " -"sale order that user want to export.\n" -" The record itself will be mapped to the " -"header part of excel sheet. The record can contain multiple one2many fields, " -"which will be written as data lines.\n" -" You can look at following instruction as " -"Excel Sheet(s), each with 1 header section (_HEAD_) and multiple row " -"sections (one2many fields)." +msgid "Export Instruction is how to write data from an active data record to specified cells in excel sheet.\n" +" For example, an active record can be a sale order that user want to export.\n" +" The record itself will be mapped to the header part of excel sheet. The record can contain multiple one2many fields, which will be written as data lines.\n" +" You can look at following instruction as Excel Sheet(s), each with 1 header section (_HEAD_) and multiple row sections (one2many fields)." msgstr "" "导出指令是如何将数据从活动数据记录写入Excel工作表中的指定单元格。\n" -" 例如,活动记录可以是用户想要导出的销售订" -"单。\n" -" 记录本身将映射到Excel工作表的标题部分。该记" -"录可以包含多个one2many字段,这些字段将写为数据行。\n" -" 您可以将以下指令看作Excel工作表,每个工作表" -"有1个标题部分(_HEAD_)和多个行部分(one2many字段)。" +" 例如,活动记录可以是用户想要导出的销售订单。\n" +" " +"记录本身将映射到Excel工作表的标题部分。该记录可以包含多个one2many字段,这些字段将写为数据行。\n" +" " +"您可以将以下指令看作Excel工作表,每个工作表有1个标题部分(_HEAD_)和多个行部分(one2many字段)。" #. module: excel_import_export #: model:ir.model.fields,field_description:excel_import_export.field_xlsx_template_export__field_name @@ -616,20 +539,15 @@ msgstr "以下是每列的详细说明:" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Following show very simple example of the dictionary construct.\n" -" Normally, this will be within templates." -"xml file within addons." +msgid "Following show very simple example of the dictionary construct.\n" +" Normally, this will be within templates.xml file within addons." msgstr "" "下面显示了字典构造的非常简单的示例。\n" -" 通常,这将位于插件中的templates.xml文件" -"中。" +" 通常,这将位于插件中的templates.xml文件中。" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"For code block ${...} and #?...?, following object " -"are available," +msgid "For code block ${...} and #?...?, following object are available," msgstr "对于代码块 ${...}#?...?, 以下对象可用," #. module: excel_import_export @@ -638,7 +556,8 @@ msgid "For code block ${...}, following object are available," msgstr "对于代码块${...}, 以下对象可用," #. module: excel_import_export -#: selection:export.xlsx.wizard,state:0 selection:import.xlsx.wizard,state:0 +#: selection:export.xlsx.wizard,state:0 +#: selection:import.xlsx.wizard,state:0 #: selection:xlsx.report,state:0 msgid "Get" msgstr "获取" @@ -706,8 +625,7 @@ msgstr "如果部分类型是行,则此字段是必需的" #. module: excel_import_export #: code:addons/excel_import_export/models/xlsx_export.py:137 #, python-format -msgid "" -"IllegalCharacterError\n" +msgid "IllegalCharacterError\n" "Some exporting data contain special character\n" "%s" msgstr "" @@ -745,24 +663,16 @@ msgstr "导入文件(*.xlsx)" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"Import Instruction is how to get data from excel sheet and write them to an " -"active record.\n" -" For example, user create a sales order " -"document, and want to import order lines from excel.\n" -" In reverse direction to exporting, data " -"from excel's cells will be mapped to record fields during import.\n" -" Cells can be mapped to record in header " -"section (_HEAD_) and data table can be mapped to row section (one2many " -"field, begins from specifed cells." +msgid "Import Instruction is how to get data from excel sheet and write them to an active record.\n" +" For example, user create a sales order document, and want to import order lines from excel.\n" +" In reverse direction to exporting, data from excel's cells will be mapped to record fields during import.\n" +" Cells can be mapped to record in header section (_HEAD_) and data table can be mapped to row section (one2many field, begins from specifed cells." msgstr "" "导入指令是如何从Excel工作表中获取数据并将其写入活动记录。\n" -" 例如,用户创建销售订单文档,并希望从excel导" -"入订单行。\n" -" 与导出相反,excel单元格中的数据将在导入期间" -"映射到记录字段。\n" -" 单元格可以映射到标题部分(_HEAD_)中的记" -"录,数据表可以映射到行部分(one2many字段,从指定的单元格开始)。" +" 例如,用户创建销售订单文档,并希望从excel导入订单行。\n" +" 与导出相反,excel单元格中的数据将在导入期间映射到记录字段。\n" +" " +"单元格可以映射到标题部分(_HEAD_)中的记录,数据表可以映射到行部分(one2many字段,从指定的单元格开始)。" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.import_xlsx_wizard @@ -771,41 +681,27 @@ msgstr "导入成功!" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"In header section part, map data fields (e.g., number, partner_id.name) into " -"cells (e.g., B1, B2)." -msgstr "" -"在头部分,将数据字段(例如,number, partner id.name)映射到单元格(例如,B1, " -"B2)。" +msgid "In header section part, map data fields (e.g., number, partner_id.name) into cells (e.g., B1, B2)." +msgstr "在头部分,将数据字段(例如,number, partner id.name)映射到单元格(例如,B1, B2)。" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"In header section, map cells (e.g., B1, B2) into data fields (e.g., number, " -"partner_id)." +msgid "In header section, map cells (e.g., B1, B2) into data fields (e.g., number, partner_id)." msgstr "在头部分,将单元格(如B1、B2)映射到数据字段(如number、合作伙伴id)。" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"In row section, data list will be rolled out from one2many row field (e.g., " -"order_line), and map data field (i.e., product_id.name, uom_id.name, qty) " -"into the first row cells to start rolling (e.g., A6, B6, C6)." +msgid "In row section, data list will be rolled out from one2many row field (e.g., order_line), and map data field (i.e., product_id.name, uom_id.name, qty) into the first row cells to start rolling (e.g., A6, B6, C6)." msgstr "" -"在行部分中,数据列表将从one2many行字段(例如,order_line)推出,并将数据字段" -"(即product_id.name,uom_id.name,qty)映射到第一行单元格以开始滚动(例如," -"A6,B6,C6)。" +"在行部分中,数据列表将从one2many行字段(例如,order_line)推出,并将数据字段(即product_id.name,uom_id.name," +"qty)映射到第一行单元格以开始滚动(例如,A6,B6,C6)。" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form -msgid "" -"In row section, data table from excel can be imported to one2many row field " -"(e.g., order_line) by mapping cells on first row onwards (e.g., A6, B6, C6) " -"to fields (e.g., product_id, uom_id, qty)" +msgid "In row section, data table from excel can be imported to one2many row field (e.g., order_line) by mapping cells on first row onwards (e.g., A6, B6, C6) to fields (e.g., product_id, uom_id, qty)" msgstr "" -"在行部分中,可以通过将第一行上的单元格(例如,A6,B6,C6)映射到字段(例如," -"product_id,uom_id,qty),将来自excel的数据表导入到one2many行字段(例如," -"order_line)" +"在行部分中,可以通过将第一行上的单元格(例如,A6,B6,C6)映射到字段(例如,product_id,uom_id,qty),将来自excel的数据表导" +"入到one2many行字段(例如,order_line)" #. module: excel_import_export #: model_terms:ir.ui.view,arch_db:excel_import_export.view_xlsx_template_form @@ -834,7 +730,7 @@ msgid "Invalid declaration, %s has no valid field type" msgstr "声明无效,%s没有有效的字段类型" #. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_import.py:222 +#: code:addons/excel_import_export/models/xlsx_import.py:217 #, python-format msgid "Invalid file style, only .xls or .xlsx file allowed" msgstr "文件样式无效,仅允许.xls或.xlsx文件" @@ -854,8 +750,7 @@ msgstr "样式类型%s的值%s无效" #. module: excel_import_export #: code:addons/excel_import_export/models/xlsx_export.py:134 #, python-format -msgid "" -"Key Error\n" +msgid "Key Error\n" "%s" msgstr "" "关键字错误\n" @@ -894,8 +789,7 @@ msgstr "最后更新时间" #. module: excel_import_export #: model:ir.model.fields,help:excel_import_export.field_xlsx_template__gname -msgid "" -"Multiple template of same model, can belong to same group,\n" +msgid "Multiple template of same model, can belong to same group,\n" "result in multiple template selection" msgstr "" "同一模型的多个模板,可以属于同一组,\n" @@ -907,7 +801,7 @@ msgid "No Delete" msgstr "不删除" #. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_import.py:254 +#: code:addons/excel_import_export/models/xlsx_import.py:249 #, python-format msgid "No data_dict['__IMPORT__'] in template %s" msgstr "模版%s中没有 data_dict['__IMPORT__']" @@ -988,10 +882,9 @@ msgid "Post Import Hook" msgstr "导入后挂钩" #. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_import.py:237 +#: code:addons/excel_import_export/models/xlsx_import.py:232 #, python-format -msgid "" -"Post import operation error\n" +msgid "Post import operation error\n" "%s" msgstr "" "发布导入操作错误\n" @@ -1130,14 +1023,12 @@ msgstr "模板名称" #. module: excel_import_export #: code:addons/excel_import_export/models/common.py:242 #, python-format -msgid "" -"Template with CSV Quoting = False, data must not contain the same char as " -"delimiter -> \"%s\"" +msgid "Template with CSV Quoting = False, data must not contain the same char as delimiter -> \"%s\"" msgstr "CSV Quoting =False的模板,数据不能包含与分隔符相同的字符->\"%s\"" #. module: excel_import_export -#: code:addons/excel_import_export/models/xlsx_export.py:228 -#: code:addons/excel_import_export/models/xlsx_import.py:249 +#: code:addons/excel_import_export/models/xlsx_export.py:230 +#: code:addons/excel_import_export/models/xlsx_import.py:244 #, python-format msgid "Template's model mismatch" msgstr "模板的模型不匹配" @@ -1160,14 +1051,8 @@ msgstr "选定的重定向操作不适用于模型%s" #. module: excel_import_export #: model:ir.model.fields,help:excel_import_export.field_ir_actions_report__report_type -msgid "" -"The type of the report that will be rendered, each one having its own " -"rendering method. HTML means the report will be opened directly in your " -"browser PDF means the report will be rendered using Wkhtmltopdf and " -"downloaded by the user." -msgstr "" -"将呈现的报告类型,每个报告都有自己的呈现方法。HTML表示报告将直接在浏览器中打" -"开PDF表示报告将使用Wkhtmltopdf呈现并由用户下载。" +msgid "The type of the report that will be rendered, each one having its own rendering method. HTML means the report will be opened directly in your browser PDF means the report will be rendered using Wkhtmltopdf and downloaded by the user." +msgstr "将呈现的报告类型,每个报告都有自己的呈现方法。HTML表示报告将直接在浏览器中打开PDF表示报告将使用Wkhtmltopdf呈现并由用户下载。" #. module: excel_import_export #: code:addons/excel_import_export/wizard/import_xlsx_wizard.py:89 @@ -1177,8 +1062,7 @@ msgstr "此导入操作在此文档上下文中不可用" #. module: excel_import_export #: model:ir.model.fields,help:excel_import_export.field_xlsx_template__show_instruction -msgid "" -"This is the computed instruction based on tab Import/Export,\n" +msgid "This is the computed instruction based on tab Import/Export,\n" "to be used by xlsx import/export engine" msgstr "" "这是基于选项卡导入/导出的计算指令,\n" diff --git a/excel_import_export/models/__init__.py b/excel_import_export/models/__init__.py index 52501c936..04a47be59 100644 --- a/excel_import_export/models/__init__.py +++ b/excel_import_export/models/__init__.py @@ -7,3 +7,17 @@ from . import xlsx_import from . import xlsx_template from . import xlsx_report from . import ir_report + +# +# +# INSERT INTO "purchase_order_line" ( +# "id", "create_uid", "create_date", +# "write_uid", "write_date", "date_planned", +# "display_type", "name", "order_id", +# "price_unit", "product_qty", "product_uom", +# "sequence") VALUES ( +# nextval('purchase_order_line_id_seq'), 2, (now() at time zone 'UTC'), +# 2, (now() at time zone 'UTC'), '2020-10-05 09:39:28', +# NULL, '[FURN_0269] Office Chair Black', 8, +# '11111.00', '5.000', 1, +# 10) diff --git a/excel_import_export/models/common.py b/excel_import_export/models/common.py index e0314904f..296ddd982 100644 --- a/excel_import_export/models/common.py +++ b/excel_import_export/models/common.py @@ -102,7 +102,7 @@ def get_field_style_cond(field): def fill_cell_style(field, field_style, styles): - field_styles = field_style.split(";") + field_styles = field_style.split(";") if field_style else [] for f in field_styles: (key, value) = f.split("=") if key not in styles.keys(): diff --git a/excel_import_export/models/styles.py b/excel_import_export/models/styles.py index 2c753f345..48d2bdaa6 100644 --- a/excel_import_export/models/styles.py +++ b/excel_import_export/models/styles.py @@ -8,7 +8,7 @@ from odoo import api, models _logger = logging.getLogger(__name__) try: - from openpyxl.styles import colors, PatternFill, Alignment, Font + from openpyxl.styles import PatternFill, Alignment, Font except ImportError: _logger.debug('Cannot import "openpyxl". Please make sure it is installed.') @@ -23,7 +23,7 @@ class XLSXStyles(models.AbstractModel): return { "font": { "bold": Font(name="Arial", size=10, bold=True), - "bold_red": Font(name="Arial", size=10, color=colors.RED, bold=True), + "bold_red": Font(name="Arial", size=10, color="FF0000", bold=True), }, "fill": { "red": PatternFill("solid", fgColor="FF0000"), diff --git a/excel_import_export/models/xlsx_export.py b/excel_import_export/models/xlsx_export.py index 2aac49b90..a8023f140 100644 --- a/excel_import_export/models/xlsx_export.py +++ b/excel_import_export/models/xlsx_export.py @@ -51,6 +51,7 @@ class XLSXExport(models.AbstractModel): """ line_field, max_row = co.get_line_max(line_field) line_field = line_field.replace("_CONT_", "") # Remove _CONT_ if any + line_field = line_field.replace("_EXTEND_", "") # Remove _EXTEND_ if any lines = record[line_field] if max_row > 0 and len(lines) > max_row: raise Exception(_("Records in %s exceed max records allowed") % line_field) @@ -89,10 +90,7 @@ class XLSXExport(models.AbstractModel): elif style is False: style = field_style_dict[field[0]] # Use default style vals[field[0]].append((value, style)) - return ( - vals, - aggre_func_dict, - ) + return (vals, aggre_func_dict) @api.model def _eval_style_cond(self, model, record, value, style_cond): @@ -185,6 +183,7 @@ class XLSXExport(models.AbstractModel): fields = ws.get(line_field, {}).values() vals, func = self._get_line_vals(record, line_field, fields) is_cont = "_CONT_" in line_field and True or False # continue row + is_extend = "_EXTEND_" in line_field and True or False # extend row cont_set = 0 rows_inserted = False # flag to insert row for rc, field in ws.get(line_field, {}).items(): @@ -200,9 +199,9 @@ class XLSXExport(models.AbstractModel): new_rc = False row_count = len(vals[field]) # Insert rows to preserve total line - if not rows_inserted: + if is_extend and not rows_inserted: rows_inserted = True - st.insert_rows(row + 1, amount=row_count - 1) + st.insert_rows(row + 1, row_count - 1) # -- for (row_val, style) in vals[field]: new_row = row + i @@ -220,6 +219,7 @@ class XLSXExport(models.AbstractModel): new_row += 1 f_rc = "{}{}".format(col, new_row) st[f_rc] = "={}({}:{})".format(f, rc, new_rc) + styles = self.env["xlsx.styles"].get_openpyxl_styles() co.fill_cell_style(st[f_rc], style, styles) cont_row = cont_row < new_row and new_row or cont_row return @@ -255,7 +255,7 @@ class XLSXExport(models.AbstractModel): content = BytesIO() wb.save(content) content.seek(0) # Set index to 0, and start reading - out_file = base64.encodestring(content.read()) + out_file = base64.encodebytes(content.read()) if record and "name" in record and record.name: out_name = record.name.replace(" ", "").replace("/", "") else: diff --git a/excel_import_export/models/xlsx_import.py b/excel_import_export/models/xlsx_import.py index 9af7b4b4f..7c4914938 100644 --- a/excel_import_export/models/xlsx_import.py +++ b/excel_import_export/models/xlsx_import.py @@ -89,18 +89,40 @@ class XLSXImport(models.AbstractModel): if line_field in record and record[line_field]: record[line_field].unlink() # Remove _NODEL_ from dict - for s, sv in data_dict.items(): - for f, fv in data_dict[s].items(): + for s, _sv in data_dict.copy().items(): + for f, _fv in data_dict[s].copy().items(): if "_NODEL_" in f: new_fv = data_dict[s].pop(f) data_dict[s][f.replace("_NODEL_", "")] = new_fv except Exception as e: raise ValidationError(_("Error deleting data\n%s") % e) + @api.model + def _get_end_row(self, st, worksheet, line_field): + """ Get max row or next empty row as the ending row """ + _x, max_row = co.get_line_max(line_field) + test_rows = {} + max_end_row = 0 + for rc, _col in worksheet.get(line_field, {}).items(): + rc, key_eval_cond = co.get_field_condition(rc) + row, col = co.pos2idx(rc) + # Use max_row, i.e., order_line[5], use it. Otherwise, use st.nrows + max_end_row = st.nrows if max_row is False else (row + max_row) + for idx in range(row, max_row and max_end_row or st.nrows): + cell_type = st.cell_type(idx, col) # empty type = 0 + r_types = test_rows.get(idx, []) + r_types.append(cell_type) + test_rows[idx] = r_types + empty_list = filter(lambda y: all(i == 0 for i in y[1]), test_rows.items()) + empty_rows = list(map(lambda z: z[0], empty_list)) + next_empty_row = empty_rows and min(empty_rows) or max_end_row + return next_empty_row + @api.model def _get_line_vals(self, st, worksheet, model, line_field): """ Get values of this field from excel sheet """ vals = {} + end_row = self._get_end_row(st, worksheet, line_field) for rc, columns in worksheet.get(line_field, {}).items(): if not isinstance(columns, list): columns = [columns] @@ -108,10 +130,11 @@ class XLSXImport(models.AbstractModel): rc, key_eval_cond = co.get_field_condition(rc) x_field, val_eval_cond = co.get_field_condition(field) row, col = co.pos2idx(rc) - out_field = "{}/{}".format(line_field, x_field) + new_line_field, _x = co.get_line_max(line_field) + out_field = "{}/{}".format(new_line_field, x_field) field_type = self._get_field_type(model, out_field) vals.update({out_field: []}) - for idx in range(row, st.nrows): + for idx in range(row, end_row): value = co._get_cell_value(st.cell(idx, col), field_type=field_type) eval_context = self.get_eval_context(model=model, value=value) if key_eval_cond: @@ -123,6 +146,53 @@ class XLSXImport(models.AbstractModel): vals.pop(out_field) return vals + @api.model + def _process_worksheet(self, wb, out_wb, out_st, model, data_dict, header_fields): + col_idx = 1 + for sheet_name in data_dict: # For each Sheet + worksheet = data_dict[sheet_name] + st = False + if isinstance(sheet_name, str): + st = co.xlrd_get_sheet_by_name(wb, sheet_name) + elif isinstance(sheet_name, int): + st = wb.sheet_by_index(sheet_name - 1) + if not st: + raise ValidationError(_("Sheet %s not found") % sheet_name) + # HEAD updates + for rc, field in worksheet.get("_HEAD_", {}).items(): + rc, key_eval_cond = co.get_field_condition(rc) + field, val_eval_cond = co.get_field_condition(field) + field_type = self._get_field_type(model, field) + value = False + try: + row, col = co.pos2idx(rc) + value = co._get_cell_value(st.cell(row, col), field_type=field_type) + except Exception: + pass + eval_context = self.get_eval_context(model=model, value=value) + if key_eval_cond: + value = str(safe_eval(key_eval_cond, eval_context)) + if val_eval_cond: + value = str(safe_eval(val_eval_cond, eval_context)) + out_st.write(0, col_idx, field) # Next Column + out_st.write(1, col_idx, value) # Next Value + header_fields.append(field) + col_idx += 1 + # Line Items + line_fields = filter(lambda x: x != "_HEAD_", worksheet) + for line_field in line_fields: + vals = self._get_line_vals(st, worksheet, model, line_field) + for field in vals: + # Columns, i.e., line_ids/field_id + out_st.write(0, col_idx, field) + header_fields.append(field) + # Data + i = 1 + for value in vals[field]: + out_st.write(i, col_idx, value) + i += 1 + col_idx += 1 + @api.model def _import_record_data(self, import_file, record, data_dict): """ From complex excel, create temp simple excel and do import """ @@ -130,9 +200,9 @@ class XLSXImport(models.AbstractModel): return try: header_fields = [] - decoded_data = base64.decodestring(import_file) + model = record._name + decoded_data = base64.decodebytes(import_file) wb = xlrd.open_workbook(file_contents=decoded_data) - col_idx = 0 out_wb = xlwt.Workbook() out_st = out_wb.add_sheet("Sheet 1") xml_id = ( @@ -143,53 +213,9 @@ class XLSXImport(models.AbstractModel): out_st.write(0, 0, "id") # id and xml_id on first column out_st.write(1, 0, xml_id) header_fields.append("id") - col_idx += 1 - model = record._name - for sheet_name in data_dict: # For each Sheet - worksheet = data_dict[sheet_name] - st = False - if isinstance(sheet_name, str): - st = co.xlrd_get_sheet_by_name(wb, sheet_name) - elif isinstance(sheet_name, int): - st = wb.sheet_by_index(sheet_name - 1) - if not st: - raise ValidationError(_("Sheet %s not found") % sheet_name) - # HEAD updates - for rc, field in worksheet.get("_HEAD_", {}).items(): - rc, key_eval_cond = co.get_field_condition(rc) - field, val_eval_cond = co.get_field_condition(field) - field_type = self._get_field_type(model, field) - value = False - try: - row, col = co.pos2idx(rc) - value = co._get_cell_value( - st.cell(row, col), field_type=field_type - ) - except Exception: - pass - eval_context = self.get_eval_context(model=model, value=value) - if key_eval_cond: - value = str(safe_eval(key_eval_cond, eval_context)) - if val_eval_cond: - value = str(safe_eval(val_eval_cond, eval_context)) - out_st.write(0, col_idx, field) # Next Column - out_st.write(1, col_idx, value) # Next Value - header_fields.append(field) - col_idx += 1 - # Line Items - line_fields = filter(lambda x: x != "_HEAD_", worksheet) - for line_field in line_fields: - vals = self._get_line_vals(st, worksheet, model, line_field) - for field in vals: - # Columns, i.e., line_ids/field_id - out_st.write(0, col_idx, field) - header_fields.append(field) - # Data - i = 1 - for value in vals[field]: - out_st.write(i, col_idx, value) - i += 1 - col_idx += 1 + # Process on all worksheets + self._process_worksheet(wb, out_wb, out_st, model, data_dict, header_fields) + # -- content = BytesIO() out_wb.save(content) content.seek(0) # Set index to 0, and start reading @@ -235,7 +261,7 @@ class XLSXImport(models.AbstractModel): _("Invalid file style, only .xls or .xlsx file allowed") ) except Exception as e: - raise ValidationError(_("Error importing data\n%s") % e) + raise e @api.model def _post_import_operation(self, record, operation): diff --git a/excel_import_export/models/xlsx_report.py b/excel_import_export/models/xlsx_report.py index fdc741458..e963752bf 100644 --- a/excel_import_export/models/xlsx_report.py +++ b/excel_import_export/models/xlsx_report.py @@ -11,8 +11,8 @@ class XLSXReport(models.AbstractModel): _name = "xlsx.report" _description = "Excel Report AbstractModel" - name = fields.Char(string="File Name", readonly=True, size=500,) - data = fields.Binary(string="File", readonly=True,) + name = fields.Char(string="File Name", readonly=True, size=500) + data = fields.Binary(string="File", readonly=True) template_id = fields.Many2one( "xlsx.template", string="Template", @@ -20,7 +20,7 @@ class XLSXReport(models.AbstractModel): ondelete="cascade", domain=lambda self: self._context.get("template_domain", []), ) - choose_template = fields.Boolean(string="Allow Choose Template", default=False,) + choose_template = fields.Boolean(string="Allow Choose Template", default=False) state = fields.Selection( [("choose", "Choose"), ("get", "Get")], default="choose", @@ -41,7 +41,6 @@ class XLSXReport(models.AbstractModel): defaults["template_id"] = len(templates) == 1 and templates.id or False return defaults - @api.multi def report_xlsx(self): self.ensure_one() Export = self.env["xlsx.export"] @@ -51,7 +50,6 @@ class XLSXReport(models.AbstractModel): "type": "ir.actions.act_window", "res_model": self._name, "view_mode": "form", - "view_type": "form", "res_id": self.id, "views": [(False, "form")], "target": "new", diff --git a/excel_import_export/models/xlsx_template.py b/excel_import_export/models/xlsx_template.py index e34528042..622e2ce68 100644 --- a/excel_import_export/models/xlsx_template.py +++ b/excel_import_export/models/xlsx_template.py @@ -7,7 +7,7 @@ from ast import literal_eval from os.path import join as opj from odoo import _, api, fields, models -from odoo.exceptions import ValidationError +from odoo.exceptions import UserError, ValidationError from odoo.modules.module import get_module_path from . import common as co @@ -24,18 +24,18 @@ class XLSXTemplate(models.Model): _description = "Excel template file and instruction" _order = "name" - name = fields.Char(string="Template Name", required=True,) + name = fields.Char(string="Template Name", required=True) res_model = fields.Char( string="Resource Model", help="The database object this attachment will be attached to.", ) - fname = fields.Char(string="File Name",) + fname = fields.Char(string="File Name") gname = fields.Char( string="Group Name", help="Multiple template of same model, can belong to same group,\n" "result in multiple template selection", ) - description = fields.Char(string="Description",) + description = fields.Char(string="Description") input_instruction = fields.Text( string="Instruction (Input)", help="This is used to construct instruction in tab Import/Export", @@ -45,8 +45,12 @@ class XLSXTemplate(models.Model): compute="_compute_output_instruction", help="Instruction on how to import/export, prepared by system.", ) - datas = fields.Binary(string="File Content",) - to_csv = fields.Boolean(string="Convert to CSV?", default=False,) + datas = fields.Binary(string="File Content") + to_csv = fields.Boolean( + string="Convert to CSV?", + default=False, + help="Convert file into CSV format on export", + ) csv_delimiter = fields.Char( string="CSV Delimiter", size=1, @@ -67,10 +71,10 @@ class XLSXTemplate(models.Model): help="Optional for CSV, default is full quoting.", ) export_ids = fields.One2many( - comodel_name="xlsx.template.export", inverse_name="template_id", + comodel_name="xlsx.template.export", inverse_name="template_id" ) import_ids = fields.One2many( - comodel_name="xlsx.template.import", inverse_name="template_id", + comodel_name="xlsx.template.import", inverse_name="template_id" ) post_import_hook = fields.Char( string="Post Import Function Hook", @@ -89,8 +93,36 @@ class XLSXTemplate(models.Model): domain=[("type", "=", "ir.actions.act_window")], help="Optional action, redirection after finish import operation", ) + # Utilities + export_action_id = fields.Many2one( + comodel_name="ir.actions.act_window", ondelete="set null", + ) + import_action_id = fields.Many2one( + comodel_name="ir.actions.act_window", ondelete="set null", + ) + use_report_wizard = fields.Boolean( + string="Easy Reporting", + help="Use common report wizard model, instead of create specific model", + ) + result_model_id = fields.Many2one( + comodel_name="ir.model", + string="Report Model", + help="When use commone wizard, choose the result model", + ) + result_field = fields.Char(compute="_compute_result_field",) + report_menu_id = fields.Many2one( + comodel_name="ir.ui.menu", string="Report Menu", readonly=True, + ) + report_action_id = fields.Many2one( + comodel_name="ir.actions.report", string="Report Action", + ) + + def _compute_result_field(self): + for rec in self: + rec.result_field = ( + ("x_%s_results" % rec.id) if rec.result_model_id else False + ) - @api.multi @api.constrains("redirect_action", "res_model") def _check_action_model(self): for rec in self: @@ -105,13 +137,13 @@ class XLSXTemplate(models.Model): ) @api.model - def load_xlsx_template(self, tempalte_ids, addon=False): - for template in self.browse(tempalte_ids): + def load_xlsx_template(self, template_ids, addon=False): + for template in self.browse(template_ids): if not addon: addon = list(template.get_external_id().values())[0].split(".")[0] addon_path = get_module_path(addon) file_path = False - for root, dirs, files in os.walk(addon_path): + for root, _dirs, files in os.walk(addon_path): for name in files: if name == template.fname: file_path = os.path.abspath(opj(root, name)) @@ -126,9 +158,11 @@ class XLSXTemplate(models.Model): rec._compute_input_export_instruction() rec._compute_input_import_instruction() rec._compute_input_post_import_hook() + if vals.get("result_model_id"): + rec._update_result_field_common_wizard() + rec._update_result_export_ids() return rec - @api.multi def write(self, vals): res = super().write(vals) if vals.get("input_instruction"): @@ -136,9 +170,89 @@ class XLSXTemplate(models.Model): rec._compute_input_export_instruction() rec._compute_input_import_instruction() rec._compute_input_post_import_hook() + if vals.get("result_model_id"): + for rec in self: + rec._update_result_field_common_wizard() + rec._update_result_export_ids() return res - @api.multi + def unlink(self): + self.env["ir.model.fields"].search( + [ + ("model", "=", "report.xlsx.wizard"), + ("name", "=", self.mapped("result_field")), + ] + ).unlink() + return super().unlink() + + def _update_result_field_common_wizard(self): + self.ensure_one() + _model = self.env["ir.model"].search([("model", "=", "report.xlsx.wizard")]) + _model.ensure_one() + _field = self.env["ir.model.fields"].search( + [("model", "=", "report.xlsx.wizard"), ("name", "=", self.result_field)] + ) + if not _field: + _field = self.env["ir.model.fields"].create( + { + "model_id": _model.id, + "name": self.result_field, + "field_description": "Results", + "ttype": "many2many", + "relation": self.result_model_id.model, + "store": False, + "depends": "res_model", + } + ) + else: + _field.ensure_one() + _field.write({"relation": self.result_model_id.model}) + _field.compute = """ +self['%s'] = self.env['%s'].search(self.safe_domain(self.domain)) + """ % ( + self.result_field, + self.result_model_id.model, + ) + + def _update_result_export_ids(self): + self.ensure_one() + results = self.env["xlsx.template.export"].search( + [("template_id", "=", self.id), ("row_field", "=", self.result_field)] + ) + if not results: + self.export_ids.unlink() + self.write( + { + "export_ids": [ + (0, 0, {"sequence": 10, "section_type": "sheet", "sheet": 1}), + ( + 0, + 0, + { + "sequence": 20, + "section_type": "row", + "row_field": self.result_field, + }, + ), + ( + 0, + 0, + { + "sequence": 30, + "section_type": "data", + "excel_cell": "A1", + "field_name": "id", + }, + ), + ], + } + ) + + @api.onchange("use_report_wizard") + def _onchange_use_report_wizard(self): + self.res_model = "report.xlsx.wizard" if self.use_report_wizard else False + self.redirect_action = False + def _compute_input_export_instruction(self): self = self.with_context(compute_from_input=True) for rec in self: @@ -166,11 +280,16 @@ class XLSXTemplate(models.Model): if "_CONT_" in row_field: is_cont = True row_field = row_field.replace("_CONT_", "") + is_extend = False + if "_EXTEND_" in row_field: + is_extend = True + row_field = row_field.replace("_EXTEND_", "") vals = { "sequence": sequence, "section_type": (row_field == "_HEAD_" and "head" or "row"), "row_field": row_field, "is_cont": is_cont, + "is_extend": is_extend, } export_lines.append((0, 0, vals)) for excel_cell, field_name in lines.items(): @@ -184,7 +303,6 @@ class XLSXTemplate(models.Model): export_lines.append((0, 0, vals)) rec.write({"export_ids": export_lines}) - @api.multi def _compute_input_import_instruction(self): self = self.with_context(compute_from_input=True) for rec in self: @@ -230,7 +348,6 @@ class XLSXTemplate(models.Model): import_lines.append((0, 0, vals)) rec.write({"import_ids": import_lines}) - @api.multi def _compute_input_post_import_hook(self): self = self.with_context(compute_from_input=True) for rec in self: @@ -238,7 +355,6 @@ class XLSXTemplate(models.Model): input_dict = literal_eval(rec.input_instruction.strip()) rec.post_import_hook = input_dict.get("__POST_IMPORT__") - @api.multi def _compute_output_instruction(self): """ From database, compute back to dictionary """ for rec in self: @@ -259,6 +375,8 @@ class XLSXTemplate(models.Model): row_field = line.row_field if line.section_type == "row" and line.is_cont: row_field = "_CONT_%s" % row_field + if line.section_type == "row" and line.is_extend: + row_field = "_EXTEND_%s" % row_field row_dict = {row_field: {}} inst_dict[itype][prev_sheet].update(row_dict) prev_row = row_field @@ -305,6 +423,101 @@ class XLSXTemplate(models.Model): inst_dict[itype] = rec.post_import_hook rec.instruction = inst_dict + def add_export_action(self): + self.ensure_one() + vals = { + "name": "Export Excel", + "res_model": "export.xlsx.wizard", + "binding_model_id": self.env["ir.model"] + .search([("model", "=", self.res_model)]) + .id, + "binding_type": "action", + "target": "new", + "view_mode": "form", + "context": """ + {'template_domain': [('res_model', '=', '%s'), + ('fname', '=', '%s'), + ('gname', '=', False)]} + """ + % (self.res_model, self.fname), + } + action = self.env["ir.actions.act_window"].create(vals) + self.export_action_id = action + + def remove_export_action(self): + self.ensure_one() + if self.export_action_id: + self.export_action_id.unlink() + + def add_import_action(self): + self.ensure_one() + vals = { + "name": "Import Excel", + "res_model": "import.xlsx.wizard", + "binding_model_id": self.env["ir.model"] + .search([("model", "=", self.res_model)]) + .id, + "binding_type": "action", + "target": "new", + "view_mode": "form", + "context": """ + {'template_domain': [('res_model', '=', '%s'), + ('fname', '=', '%s'), + ('gname', '=', False)]} + """ + % (self.res_model, self.fname), + } + action = self.env["ir.actions.act_window"].create(vals) + self.import_action_id = action + + def remove_import_action(self): + self.ensure_one() + if self.import_action_id: + self.import_action_id.unlink() + + def add_report_menu(self): + self.ensure_one() + if not self.fname: + raise UserError(_("No file content!")) + # Create report action + vals = { + "name": self.name, + "report_type": "excel", + "model": "report.xlsx.wizard", + "report_name": self.fname, + "report_file": self.fname, + } + report_action = self.env["ir.actions.report"].create(vals) + self.report_action_id = report_action + # Create window action + vals = { + "name": self.name, + "res_model": "report.xlsx.wizard", + "binding_type": "action", + "target": "new", + "view_mode": "form", + "context": { + "report_action_id": report_action.id, + "default_res_model": self.result_model_id.model, + }, + } + action = self.env["ir.actions.act_window"].create(vals) + # Create menu + vals = { + "name": self.name, + "action": "{},{}".format(action._name, action.id), + } + menu = self.env["ir.ui.menu"].create(vals) + self.report_menu_id = menu + + def remove_report_menu(self): + self.ensure_one() + if self.report_action_id: + self.report_action_id.unlink() + if self.report_menu_id: + self.report_menu_id.action.unlink() + self.report_menu_id.unlink() + class XLSXTemplateImport(models.Model): _name = "xlsx.template.import" @@ -318,15 +531,15 @@ class XLSXTemplateImport(models.Model): ondelete="cascade", readonly=True, ) - sequence = fields.Integer(string="Sequence", default=10,) - sheet = fields.Char(string="Sheet",) + sequence = fields.Integer(string="Sequence", default=10) + sheet = fields.Char(string="Sheet") section_type = fields.Selection( [("sheet", "Sheet"), ("head", "Head"), ("row", "Row"), ("data", "Data")], string="Section Type", required=True, ) row_field = fields.Char( - string="Row Field", help="If section type is row, this field is required", + string="Row Field", help="If section type is row, this field is required" ) no_delete = fields.Boolean( string="No Delete", @@ -334,9 +547,9 @@ class XLSXTemplateImport(models.Model): help="By default, all rows will be deleted before import.\n" "Select No Delete, otherwise", ) - excel_cell = fields.Char(string="Cell",) - field_name = fields.Char(string="Field",) - field_cond = fields.Char(string="Field Cond.",) + excel_cell = fields.Char(string="Cell") + field_name = fields.Char(string="Field") + field_cond = fields.Char(string="Field Cond.") @api.model def create(self, vals): @@ -348,9 +561,7 @@ class XLSXTemplateImport(models.Model): if self._context.get("compute_from_input") and vals.get("field_name"): field_name, field_cond = co.get_field_condition(vals["field_name"]) field_cond = field_cond and "${%s}" % (field_cond or "") or False - vals.update( - {"field_name": field_name, "field_cond": field_cond,} - ) + vals.update({"field_name": field_name, "field_cond": field_cond}) return vals @@ -366,25 +577,30 @@ class XLSXTemplateExport(models.Model): ondelete="cascade", readonly=True, ) - sequence = fields.Integer(string="Sequence", default=10,) - sheet = fields.Char(string="Sheet",) + sequence = fields.Integer(string="Sequence", default=10) + sheet = fields.Char(string="Sheet") section_type = fields.Selection( [("sheet", "Sheet"), ("head", "Head"), ("row", "Row"), ("data", "Data")], string="Section Type", required=True, ) row_field = fields.Char( - string="Row Field", help="If section type is row, this field is required", + string="Row Field", help="If section type is row, this field is required" ) is_cont = fields.Boolean( - string="Continue", default=False, help="Continue data rows after last data row", + string="Continue", default=False, help="Continue data rows after last data row" ) - excel_cell = fields.Char(string="Cell",) - field_name = fields.Char(string="Field",) - field_cond = fields.Char(string="Field Cond.",) - is_sum = fields.Boolean(string="Sum", default=False,) - style = fields.Char(string="Default Style",) - style_cond = fields.Char(string="Style w/Cond.",) + is_extend = fields.Boolean( + string="Extend", + default=False, + help="Extend a blank row after filling each record, to extend the footer", + ) + excel_cell = fields.Char(string="Cell") + field_name = fields.Char(string="Field") + field_cond = fields.Char(string="Field Cond.") + is_sum = fields.Boolean(string="Sum", default=False) + style = fields.Char(string="Default Style") + style_cond = fields.Char(string="Style w/Cond.") @api.model def create(self, vals): diff --git a/excel_import_export/readme/HISTORY.rst b/excel_import_export/readme/HISTORY.rst index c6e2a27cf..8aa1176a5 100644 --- a/excel_import_export/readme/HISTORY.rst +++ b/excel_import_export/readme/HISTORY.rst @@ -1,3 +1,11 @@ +13.0.1.0.0 (2020-08-23) +~~~~~~~~~~~~~~~~~~~~~~~ + +* Migration to Odoo 13 +* Enhancement on usability, to be more configurable instead of coding + * Import/Export now have "Add/Remove Export Action", "Add/Remove Import Action" + * "Easy Report" option which allow user to create export directly by config only. + 12.0.1.0.5 (2019-12-19) ~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/excel_import_export/readme/INSTALL.rst b/excel_import_export/readme/INSTALL.rst index f64a90e5b..f53012c54 100644 --- a/excel_import_export/readme/INSTALL.rst +++ b/excel_import_export/readme/INSTALL.rst @@ -2,4 +2,4 @@ To install this module, you need to install following python library, **xlrd, xl Then, simply install **excel_import_export**. -For demo, install **excel_import_export_demo**. +For demo, install **excel_import_export_demo** diff --git a/excel_import_export/readme/ROADMAP.rst b/excel_import_export/readme/ROADMAP.rst index 21040a2d2..304d073d1 100644 --- a/excel_import_export/readme/ROADMAP.rst +++ b/excel_import_export/readme/ROADMAP.rst @@ -1,2 +1 @@ - Module extension e.g., excel_import_export_async, that add ability to execute as async process. -- Ability to add contextual action in XLSX Tempalte, e.g., Add import action, Add export action. In similar manner as in Server Action. diff --git a/excel_import_export/readme/USAGE.rst b/excel_import_export/readme/USAGE.rst index ef4a1f291..7be6909c8 100644 --- a/excel_import_export/readme/USAGE.rst +++ b/excel_import_export/readme/USAGE.rst @@ -1,3 +1,6 @@ +Concepts +-------- + This module contain pre-defined function and wizards to make exporting, importing and reporting easy. At the heart of this module, there are 2 `main methods` @@ -13,6 +16,9 @@ After install this module, go to Settings > Excel Import/Export > XLSX Templates As this module provide tools, it is best to explain as use cases. For example use cases, please install **excel_import_export_demo** +Use Cases +--------- + **Use Case 1:** Export/Import Excel on existing document This add export/import action menus in existing document (example - excel_import_export_demo/import_export_sale_order) @@ -59,3 +65,24 @@ Please see example in excel_import_export_demo/report_action, which shows, 1. Print excel from an active sale.order 2. Run partner list report based on search criteria. + +Easy Reporting Option +--------------------- + +Technically, this option is the same as "Create Excel Report" use case. But instead of having to write XML / Python code like normally do, +this option allow user to create a report based on a model or view, all by configuration only. + +1. Goto > Technical> Excel Import/Export > XLSX Templates, and create a new template for a report. +2. On the new template, select "Easy Reporting" option, then select followings + - Report Model, this can be data model or data view we want to get the results from. + - Click upload your file and add the excel template (.xlsx) + - Click Save, system will create sample export line, user can add more fields according to results model. +3. Click Add Report Menu, the report menu will be created, user can change its location. Now the report is ready to use. + + .. figure:: ../static/description/xlsx_template.png + :width: 800 px + +Note: Using easy reporting mode, system will used a common criteria wizard. + + .. figure:: ../static/description/common_wizard.png + :width: 800 px diff --git a/excel_import_export/static/description/common_wizard.png b/excel_import_export/static/description/common_wizard.png new file mode 100644 index 000000000..0fb954079 Binary files /dev/null and b/excel_import_export/static/description/common_wizard.png differ diff --git a/excel_import_export/static/description/index.html b/excel_import_export/static/description/index.html index e0b8816d6..17eebfbfb 100644 --- a/excel_import_export/static/description/index.html +++ b/excel_import_export/static/description/index.html @@ -379,35 +379,34 @@ ul.auto-toc {

Table of contents

-

Installation

+

Installation

To install this module, you need to install following python library, xlrd, xlwt, openpyxl.

Then, simply install excel_import_export.

For demo, install excel_import_export_demo.

-

Usage

+

Usage

This module contain pre-defined function and wizards to make exporting, importing and reporting easy.

At the heart of this module, there are 2 main methods

    @@ -463,53 +462,47 @@ Please see example in excel_import_export_demo/report_action, which shows,

-

Known issues / Roadmap

+

Known issues / Roadmap

  • Module extension e.g., excel_import_export_async, that add ability to execute as async process.
  • Ability to add contextual action in XLSX Tempalte, e.g., Add import action, Add export action. In similar manner as in Server Action.
-

Changelog

+

Changelog

-

12.0.1.0.5 (2019-12-19)

-
    -
  • Speed up export when dealing with many rows
  • -
-
- -
-

12.0.1.0.3 (2019-08-09)

+
+

12.0.1.0.3 (2019-08-09)

  • Add report action for report_type = ‘excel’
-
-

12.0.1.0.2 (2019-08-07)

+
+

12.0.1.0.2 (2019-08-07)

  • Small fix, to ensure that system parameter ‘path_temp_file’ (ir.config_parameter) is readable
-
-

12.0.1.0.1 (2019-06-24)

+
+

12.0.1.0.1 (2019-06-24)

-
-

Bug Tracker

+

Bug Tracker

Bugs are tracked on GitHub Issues. In case of trouble, please check there if your issue has already been reported. If you spotted it first, help us smashing it by providing a detailed and welcomed @@ -517,22 +510,22 @@ If you spotted it first, help us smashing it by providing a detailed and welcome

Do not contact contributors directly about support or help with technical issues.

-

Credits

+

Credits

-

Authors

+

Authors

  • Ecosoft
-

Maintainers

+

Maintainers

This module is maintained by the OCA.

Odoo Community Association

OCA, or the Odoo Community Association, is a nonprofit organization whose diff --git a/excel_import_export/static/description/xlsx_template.png b/excel_import_export/static/description/xlsx_template.png new file mode 100644 index 000000000..c4bdc37f9 Binary files /dev/null and b/excel_import_export/static/description/xlsx_template.png differ diff --git a/excel_import_export/static/src/js/report/action_manager_report.js b/excel_import_export/static/src/js/report/action_manager_report.js index 6b1330705..482e22fa8 100644 --- a/excel_import_export/static/src/js/report/action_manager_report.js +++ b/excel_import_export/static/src/js/report/action_manager_report.js @@ -1,21 +1,21 @@ -// Copyright 2019 Ecosoft Co., Ltd. +// © 2017 Creu Blanca // License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html). odoo.define("excel_import_export.report", function(require) { "use strict"; var core = require("web.core"); var ActionManager = require("web.ActionManager"); - var crash_manager = require("web.crash_manager"); var framework = require("web.framework"); var session = require("web.session"); var _t = core._t; ActionManager.include({ _downloadReportExcel: function(url, actions) { + var self = this; framework.blockUI(); - var def = $.Deferred(); var type = "excel"; var cloned_action = _.clone(actions); + var new_url = url; if ( _.isUndefined(cloned_action.data) || @@ -23,41 +23,42 @@ odoo.define("excel_import_export.report", function(require) { (_.isObject(cloned_action.data) && _.isEmpty(cloned_action.data)) ) { if (cloned_action.context.active_ids) { - url += "/" + cloned_action.context.active_ids.join(","); + new_url += "/" + cloned_action.context.active_ids.join(","); } } else { - url += + new_url += "?options=" + encodeURIComponent(JSON.stringify(cloned_action.data)); - url += + new_url += "&context=" + encodeURIComponent(JSON.stringify(cloned_action.context)); } - var blocked = !session.get_file({ - url: url, - data: { - data: JSON.stringify([url, type]), - }, - success: def.resolve.bind(def), - error: function() { - crash_manager.rpc_error.apply(crash_manager, arguments); - def.reject(); - }, - complete: framework.unblockUI, + return new Promise(function(resolve, reject) { + var blocked = !session.get_file({ + url: new_url, + data: { + data: JSON.stringify([new_url, type]), + }, + success: resolve, + error: error => { + self.call("crash_manager", "rpc_error", error); + reject(); + }, + complete: framework.unblockUI, + }); + if (blocked) { + // AAB: this check should be done in get_file service directly, + // should not be the concern of the caller (and that way, get_file + // could return a deferred) + var message = _t( + "A popup window with your report was blocked. You " + + "may need to change your browser settings to allow " + + "popup windows for this page." + ); + this.do_warn(_t("Warning"), message, true); + } }); - if (blocked) { - // AAB: this check should be done in get_file service directly, - // should not be the concern of the caller (and that way, get_file - // could return a deferred) - var message = _t( - "A popup window with your report was blocked. You " + - "may need to change your browser settings to allow " + - "popup windows for this page." - ); - this.do_warn(_t("Warning"), message, true); - } - return def; }, _triggerDownload: function(action, options, type) { diff --git a/excel_import_export/views/xlsx_template_view.xml b/excel_import_export/views/xlsx_template_view.xml index ac0727148..697993003 100644 --- a/excel_import_export/views/xlsx_template_view.xml +++ b/excel_import_export/views/xlsx_template_view.xml @@ -16,6 +16,25 @@

+
+

@@ -35,6 +54,20 @@ name="csv_quote" attrs="{'invisible': [('to_csv', '=', False)]}" /> + + + + @@ -46,6 +79,26 @@ +
+
+ @@ -83,6 +136,11 @@ attrs="{'required': [('section_type', 'in', ('head', 'row'))], 'invisible': [('section_type', 'not in', ('head', 'row'))]}" /> + + +
+
+ @@ -246,7 +326,9 @@
  • Sheet: Name (e.g., Sheet 1) or index (e.g., 1) of excel sheet
  • Row Field: Use _HEAD_ for the record itself, and one2many field (e.g., line_ids) for row data
  • + >Row Field: Use _HEAD_ for the record itself, and one2many field for row data, e.g., order_line, line_ids[max_row] where [max_row] is optional number of rows to import
  • No Delete: By default, all one2many lines will be deleted before import. Select this, to avoid deletion
  • XLSX Templates ir.actions.act_window xlsx.template - form tree,form

    diff --git a/excel_import_export/wizard/__init__.py b/excel_import_export/wizard/__init__.py index 136b4ff0c..ffdeb0d0a 100644 --- a/excel_import_export/wizard/__init__.py +++ b/excel_import_export/wizard/__init__.py @@ -1,2 +1,3 @@ from . import export_xlsx_wizard from . import import_xlsx_wizard +from . import report_xlsx_wizard diff --git a/excel_import_export/wizard/export_xlsx_wizard.py b/excel_import_export/wizard/export_xlsx_wizard.py index be63c745f..368a7edb4 100644 --- a/excel_import_export/wizard/export_xlsx_wizard.py +++ b/excel_import_export/wizard/export_xlsx_wizard.py @@ -12,8 +12,8 @@ class ExportXLSXWizard(models.TransientModel): _name = "export.xlsx.wizard" _description = "Wizard for exporting excel" - name = fields.Char(string="File Name", readonly=True, size=500,) - data = fields.Binary(string="File", readonly=True,) + name = fields.Char(string="File Name", readonly=True, size=500) + data = fields.Binary(string="File", readonly=True) template_id = fields.Many2one( "xlsx.template", string="Template", @@ -21,9 +21,9 @@ class ExportXLSXWizard(models.TransientModel): ondelete="cascade", domain=lambda self: self._context.get("template_domain", []), ) - res_id = fields.Integer(string="Resource ID", readonly=True, required=True,) + res_id = fields.Integer(string="Resource ID", readonly=True, required=True) res_model = fields.Char( - string="Resource Model", readonly=True, required=True, size=500, + string="Resource Model", readonly=True, required=True, size=500 ) state = fields.Selection( [("choose", "Choose"), ("get", "Get")], @@ -49,7 +49,6 @@ class ExportXLSXWizard(models.TransientModel): defaults["res_model"] = res_model return defaults - @api.multi def action_export(self): self.ensure_one() Export = self.env["xlsx.export"] @@ -61,7 +60,6 @@ class ExportXLSXWizard(models.TransientModel): "type": "ir.actions.act_window", "res_model": "export.xlsx.wizard", "view_mode": "form", - "view_type": "form", "res_id": self.id, "views": [(False, "form")], "target": "new", diff --git a/excel_import_export/wizard/import_xlsx_wizard.py b/excel_import_export/wizard/import_xlsx_wizard.py index 3c785814d..7736b27dc 100644 --- a/excel_import_export/wizard/import_xlsx_wizard.py +++ b/excel_import_export/wizard/import_xlsx_wizard.py @@ -12,19 +12,19 @@ class ImportXLSXWizard(models.TransientModel): _name = "import.xlsx.wizard" _description = "Wizard for importing excel" - import_file = fields.Binary(string="Import File (*.xlsx)",) + import_file = fields.Binary(string="Import File (*.xlsx)") template_id = fields.Many2one( "xlsx.template", string="Template", required=True, - ondelete="set null", + ondelete="cascade", domain=lambda self: self._context.get("template_domain", []), ) - res_id = fields.Integer(string="Resource ID", readonly=True,) - res_model = fields.Char(string="Resource Model", readonly=True, size=500,) - datas = fields.Binary(string="Sample", related="template_id.datas", readonly=True,) + res_id = fields.Integer(string="Resource ID", readonly=True) + res_model = fields.Char(string="Resource Model", readonly=True, size=500) + datas = fields.Binary(string="Sample", related="template_id.datas", readonly=True) fname = fields.Char( - string="Template Name", related="template_id.fname", readonly=True, + string="Template Name", related="template_id.fname", readonly=True ) attachment_ids = fields.Many2many( "ir.attachment", @@ -108,7 +108,6 @@ class ImportXLSXWizard(models.TransientModel): defaults["res_model"] = res_model return defaults - @api.multi def get_import_sample(self): self.ensure_one() return { @@ -116,14 +115,12 @@ class ImportXLSXWizard(models.TransientModel): "type": "ir.actions.act_window", "res_model": "import.xlsx.wizard", "view_mode": "form", - "view_type": "form", "res_id": self.id, "views": [(False, "form")], "target": "new", "context": self._context.copy(), } - @api.multi def action_import(self): self.ensure_one() Import = self.env["xlsx.import"] @@ -149,7 +146,6 @@ class ImportXLSXWizard(models.TransientModel): "type": "ir.actions.act_window", "res_model": self._name, "view_mode": "form", - "view_type": "form", "res_id": self.id, "views": [(False, "form")], "target": "new", diff --git a/excel_import_export/wizard/report_xlsx_wizard.py b/excel_import_export/wizard/report_xlsx_wizard.py new file mode 100644 index 000000000..4647153b5 --- /dev/null +++ b/excel_import_export/wizard/report_xlsx_wizard.py @@ -0,0 +1,22 @@ +# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) +import ast + +from odoo import fields, models + + +class ReportXLSXWizard(models.TransientModel): + _name = "report.xlsx.wizard" + _description = "Generic Report Wizard, used with template reporting option" + + res_model = fields.Char() + domain = fields.Char(string="Search Criterias") + + def action_report(self): + action_id = self._context.get("report_action_id") + action = self.env["ir.actions.report"].browse(action_id) + res = action.read()[0] + return res + + def safe_domain(self, str_domain): + return ast.literal_eval(str_domain or "[]") diff --git a/excel_import_export/wizard/report_xlsx_wizard.xml b/excel_import_export/wizard/report_xlsx_wizard.xml new file mode 100644 index 000000000..7686749c5 --- /dev/null +++ b/excel_import_export/wizard/report_xlsx_wizard.xml @@ -0,0 +1,31 @@ + + + + + report.xlsx.wizard + report.xlsx.wizard + + + + + + +

    + +
    + +