ソースを参照

成功完成搜索竞品表格的生成

mrh 1 年間 前
コミット
c8cb1a380c
3 ファイル変更78 行追加16 行削除
  1. 0 1
      docs/gpt/to_excel.md
  2. 26 15
      src/excel_tools/excel_writer.py
  3. 52 0
      tests/mytest/t_openxyl.py

+ 0 - 1
docs/gpt/to_excel.md

@@ -51,7 +51,6 @@
 
 目前生成的excel存在问题:
 - 每列的 “搜索量” 超过1w没有标红
-- product_info 产品信息需要与最后一行隔开。并且限制它的宽度,因为它太长了,导致整列很宽。目前仍然没有解决宽度问题,是否要设置整列的宽度?它与 asin ,例如 "B0CQ1SHD8V" "traffic_keyword"字段 来自同一列
 
 
 # 生成 excel 

+ 26 - 15
src/excel_tools/excel_writer.py

@@ -13,7 +13,7 @@ from utils.file import read_file
 from utils.logu import logger
 
 # 样式常量
-RED_FILL = PatternFill(start_color='FFFF0000', fill_type='solid')
+RED_FILL = PatternFill(start_color='FF0000',end_color="FF0000", fill_type='solid')  # 修正为RGB格式
 HEADER_FONT = Font(bold=True, color='FFFFFF')
 HEADER_FILL = PatternFill(start_color='4F81BD', patternType='solid')
 COLUMN_SPACING = 3  # 每个产品占3列(关键词、搜索量、空列)
@@ -70,6 +70,7 @@ class ExcelGenerator:
         self.output_path = Path(output_path)
         self.current_col = 1
         self.max_data_rows = 0  # 记录最大数据行数
+        self.product_cols = []  # 记录所有产品起始列
         
     def add_product(self, json_path: str, asin: str):
         """添加产品数据"""
@@ -78,6 +79,9 @@ class ExcelGenerator:
             data = json.loads(read_file(json_path))
             processor = ProductDataProcessor(data, asin)
             
+            # 记录产品起始列
+            self.product_cols.append(self.current_col)
+            
             # 写入主数据表
             self._write_main_table(processor, asin)
             
@@ -123,11 +127,12 @@ class ExcelGenerator:
                 kw_cell.font = Font(color='0000FF', underline='single')  # 添加蓝色下划线样式
             
             # 搜索量
-            search_cell = self.ws.cell(data_row, self.current_col + 1, row['monthly_searches'])
-            search_cell.number_format = '#,##0'
+            search_cell = self.ws.cell(data_row, self.current_col + 1, int(row['monthly_searches']))
+            search_cell.number_format = 'General'
+            search_cell.value = int(search_cell.value)  # 确保存储为整数类型
         
         # 更新最大行数
-        self.max_data_rows = max(self.max_data_rows, len(df) + 1)
+        self.max_data_rows = max(self.max_data_rows, len(df) + 2)  # 修正最大行号计算
         
         # 设置初始列宽
         self.ws.column_dimensions[get_column_letter(self.current_col)].width = 35
@@ -183,22 +188,28 @@ class ExcelGenerator:
 
     def _apply_conditional_formatting(self):
         """应用条件格式"""
+        # 修正颜色定义(使用RGB格式)
+        
+        # 创建条件格式规则(移除字体设置)
         red_rule = CellIsRule(
             operator='greaterThan',
-            formula=['10000'],  # 1万阈值
+            formula=['10000'],
+            stopIfTrue=True,
             fill=RED_FILL
         )
         
-        # 精确应用条件格式到每个产品的搜索量列(current_col+1)
-        # 遍历每个产品的搜索量列(current_col +1 的步进)
-        for col in range(1, self.current_col, COLUMN_SPACING):
-            search_col = col + 1  # 每个产品的搜索量列
-            col_letter = get_column_letter(search_col)
-            # 应用格式到整个数据区域
-            self.ws.conditional_formatting.add(
-                f'{col_letter}3:{col_letter}{self.max_data_rows}',
-                red_rule
-            )
+        # 计算目标列字母(B=2, E=5, H=8...)
+        target_columns = []
+        # 使用记录的product_cols计算目标列
+        for start_col in self.product_cols:
+            search_col = start_col + 1  # 搜索量列是起始列+1
+            target_columns.append(get_column_letter(search_col))
+        
+        # 应用条件格式到所有目标列
+        for col_letter in target_columns:
+            cell_range = f"{col_letter}3:{col_letter}{self.max_data_rows}"
+            self.ws.conditional_formatting.add(cell_range, red_rule)
+            logger.info(f"应用条件格式到 {cell_range} (值 > 10000)")
 
     def _adjust_column_widths(self):
         """自动调整列宽"""

+ 52 - 0
tests/mytest/t_openxyl.py

@@ -0,0 +1,52 @@
+from openpyxl import Workbook
+from openpyxl.styles import PatternFill
+from openpyxl.formatting.rule import CellIsRule
+from utils.logu import get_logger
+logger = get_logger('test')
+# 创建新工作簿和工作表
+wb = Workbook()
+ws = wb.active
+
+# 先填充示例数据(实际使用时替换为你的真实数据)
+data = [
+    # B   C D E   F G H   I J K   L
+    [5000, 0, 0, 8000, 0, 0, 15000, 0, 0, 20000],  # 第1行
+    [12000, 0, 0, 9500, 0, 0, 8000, 0, 0, 5000],   # 第2行
+    [9000, 0, 0, 11000, 0, 0, 13000, 0, 0, 9999]   # 第3行
+]
+
+for row in data:
+    ws.append(row)
+
+# 创建红色填充样式
+red_fill = PatternFill(
+    start_color="FF0000",  # 红色
+    end_color="FF0000",
+    fill_type="solid"
+)
+
+# 配置参数
+threshold = 10000          # 阈值
+target_columns = ['A', 'D', 'H', 'K']  # 要设置条件格式的列
+
+# 获取实际数据范围的最大行数
+max_row = ws.max_row
+
+# 为每个目标列添加条件格式
+for col in target_columns:
+    # 构造列范围(例如:B1:B3)
+    cell_range = f"{col}1:{col}{max_row}"
+    
+    # 创建条件格式规则
+    rule = CellIsRule(
+        operator='greaterThan', 
+        formula=[threshold],  # 注意参数是列表类型
+        stopIfTrue=True,      # 遇到符合条件的单元格后停止其他规则检查
+        fill=red_fill
+    )
+    
+    # 将规则应用到工作表
+    ws.conditional_formatting.add(cell_range, rule)
+    logger.info(f"应用条件格式到 {cell_range} (值 > 10000) {rule}")
+# 保存工作簿
+wb.save("conditional_formatting_example.xlsx")