自定义路径导入xlwt出现AttributeError问题的解决咨询
It sounds like the issue stems from how your import statements are referencing the xlwt library when it's placed in your custom Odoo addon path. Let's break down the problem and walk through actionable solutions:
Root Cause
In your original working code, you import xlwt and Borders from the standard Python path. When you move xlwt to odoo.addons.inventory.python_lib, if you only update the first import but leave from xlwt import Borders as-is, Python will still look for the standard xlwt package (which might not be installed). This causes the entire try block to fail, triggering the except clause that sets xlwt = None—hence the error when you try to call xlwt.Workbook().
Solution 1: Fix Import Statements to Use Custom Path
Update both imports to explicitly reference your custom xlwt location. You have two clean ways to do this:
Option A: Fully Qualified Imports
try: # Import xlwt from your custom addon path from odoo.addons.inventory.python_lib import xlwt # Import Borders from the same custom xlwt package from odoo.addons.inventory.python_lib.xlwt import Borders except ImportError: xlwt = None
Option B: Reuse the Imported xlwt Module
Since you've already imported the custom xlwt module, you can access Borders directly from it instead of a separate import:
try: from odoo.addons.inventory.python_lib import xlwt # Access Borders from the already imported xlwt module Borders = xlwt.Borders except ImportError: xlwt = None
Solution 2: Add Custom Path to sys.path
If you prefer to keep your original import syntax (import xlwt), explicitly add your python_lib folder to Python's system path before importing. This tells Python to look in your custom location first:
import sys import os # Get the absolute path to your addon's python_lib directory addon_dir = os.path.dirname(os.path.abspath(__file__)) custom_lib_path = os.path.join(addon_dir, "python_lib") # Add the path if it's not already in sys.path if custom_lib_path not in sys.path: sys.path.append(custom_lib_path) # Now import xlwt normally—it will load from your custom path try: import xlwt from xlwt import Borders except ImportError: xlwt = None
Additional Checks
- Verify Package Structure: Ensure the entire xlwt library folder is copied into
python_lib(including all.pyfiles and__init__.py—don't just copy parts of it). - Confirm Addon is Enabled: Make sure your
inventoryaddon is installed and activated in your Odoo instance. If the addon isn't loaded, theodoo.addons.inventoryimport path won't be available.
Once you implement one of these fixes, your workbook = xlwt.Workbook() call should work as expected.
内容的提问来源于stack exchange,提问作者Harshit Trivedi

