Spaces:
Sleeping
Sleeping
Update app.py
Browse files14 unmodified lines15161718192019 unmodified lines40414243444512 unmodified lines58596061626329 unmodified lines93949596979819 unmodified lines11811912012112212313 unmodified lines13713813914014114221 unmodified lines16416516616716816938 unmodified lines2082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782793 unmodified lines28328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331414 unmodified lines3293303313323333343353363373383393403413423433443453463473483493503513523533543553561 unmodified line35835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149214 unmodified linesfrom openpyxl.utils import get_column_letterfrom openpyxl.utils.cell import column_index_from_stringfrom openpyxl.utils.cell import coordinate_from_stringst.set_page_config(page_title="竞品对比", layout="wide")19 unmodified linesif not os.path.exists(image_dir):os.makedirs(image_dir)def extract_images_from_excel(excel_file_path):"""从Excel文件中提取嵌入的图片"""# 创建临时目录12 unmodified lines# 加载Excel以获取ASIN列df = pd.read_excel(excel_file_path, engine='openpyxl')# 获取所有ASIN及其在DataFrame中的顺序asins = []for i, row in df.iterrows():29 unmodified linesif img_idx in image_files:img_path = image_files[img_idx]target_path = os.path.join(image_dir, f"{asin}.png")shutil.copy2(img_path, target_path)asin_to_image[asin] = target_path19 unmodified linesif img_idx in image_files:img_path = image_files[img_idx]target_path = os.path.join(image_dir, f"{asin}.png")shutil.copy2(img_path, target_path)asin_to_image[asin] = target_pathexcept Exception as e:13 unmodified linesimg_idx = sorted_img_indices[i]img_path = image_files[img_idx]target_path = os.path.join(image_dir, f"{asin}.png")shutil.copy2(img_path, target_path)asin_to_image[asin] = target_path21 unmodified lines# 读取Excel文件df = pd.read_excel(temp_file, engine='openpyxl')# 提取所有ASIN值asins = df['ASIN'].dropna().unique().tolist()38 unmodified lines# 过滤选中的ASIN数据filtered_df = df[df['ASIN'].isin(final_selected_asins)]# 创建一个空列表用于存储结果数据result_data = []# 处理每个选中的ASINfor i, (idx, row) in enumerate(filtered_df.iterrows()):current_asin = row.get("ASIN", "")if not isinstance(current_asin, str):current_asin = str(current_asin) # 确保ASIN是字符串# 创建新行数据new_row = {}# 检查是否有对应的图片if current_asin in asin_to_image:new_row["图片"] = asin_to_image[current_asin]else:new_row["图片"] = ""# 提取其他字段并确保所有值都是字符串new_row["品牌"] = str(row.get("品牌", ""))new_row["品牌链接"] = str(row.get("品牌链接", ""))new_row["ASIN"] = current_asinnew_row["近30天月销量"] = str(row.get("月销量", ""))# 处理月销售额 - 匹配开头monthly_sales_found = Falsefor col in df.columns:if "月销售额" in col:new_row["近30天月销售额"] = str(row.get(col, ""))monthly_sales_found = Truebreak2 unmodified lines# 处理价格 - 匹配开头price_found = Falsefor col in df.columns:if "价格" in col:new_row["价格"] = str(row.get(col, ""))price_found = Truebreakif not price_found:new_row["价格"] = ""new_row["变体"] = str(row.get("变体数", ""))new_row["RV数量"] = str(row.get("评分数", ""))new_row["RV评分"] = str(row.get("评分", ""))new_row["上架时间"] = str(row.get("上架时间", ""))# 处理重量 - 优先查找"重量.1"列,其次查找包含g的值weight_found = False# 优先查找"重量.1"列if "重量.1" in df.columns:value = str(row.get("重量.1", "")).strip()if value:new_row["重量(g)"] = valueweight_found = True# 如果没找到,再查找所有包含"重量"且以g结尾的列if not weight_found:for col in df.columns:if "重量" in col:value = str(row.get(col, "")).strip()if value.lower().endswith("g"):new_row["重量(g)"] = valueweight_found = Truebreakif not weight_found:3 unmodified linessize_found = False# 首先检查"体积.1"列if "体积.1" in df.columns:value = str(row.get("体积.1", "")).strip()if value:new_row["尺寸(cm)"] = valuesize_found = True# 如果没找到,再搜索其他可能包含尺寸的列if not size_found:for col in df.columns:if any(term in col for term in ["尺寸", "体积"]):value = str(row.get(col, "")).strip()if "cm" in value.lower() or " x " in value.lower():new_row["尺寸(cm)"] = valuesize_found = Truebreakif not size_found:new_row["尺寸(cm)"] = ""# 将新行添加到结果列表result_data.append(new_row)# 创建结果DataFramecolumns = ["图片", "品牌", "品牌链接", "ASIN", "近30天月销量", "近30天月销售额","价格", "变体", "RV数量", "RV评分", "上架时间", "重量(g)", "尺寸(cm)"]result_df = pd.DataFrame(result_data, columns=columns)# 显示结果表格 - 使用转换为字符串的方式避免Arrow错误st.subheader("提取结果")14 unmodified linesws = wb.activews.title = "提取结果"# 合并A列和B列for i in range(1, len(transposed_df.index) + 1):ws.merge_cells(f'A{i}:B{i}')# 写入标题行 - 写入到合并后的A列for i, field in enumerate(transposed_df.index):# 写入到合并单元格的左上角单元格ws.cell(row=i+1, column=1).value = field# 写入数据 - 每个ASIN一列,从第三列开始for col_idx, asin in enumerate(transposed_df.columns):# 列标题是ASINcol_pos = col_idx + 3 # 第二列是字段名称,从第三列开始数据# 写入每个字段的值,跳过"图片"行for row_idx, field in enumerate(transposed_df.index):if field == "图片":continue # 不写入图片行的内容cell = ws.cell(row=row_idx+1, column=col_pos)cell.value = str(transposed_df.loc[field, asin]) # 确保是字符串# 设置单元格样式thin_border = Border(left=Side(style='thin'),right=Side(style='thin'),1 unmodified linebottom=Side(style='thin'))center_aligned = Alignment(horizontal='center', vertical='center', wrap_text=True)bold_font = Font(bold=True)# 遍历所有单元格设置边框和居中对齐for row in ws.iter_rows():for cell in row:cell.border = thin_bordercell.alignment = center_aligned# 为合并后的字段名称(标题)设置加粗字体for row_idx in range(1, len(transposed_df.index) + 1):# 由于A列和B列已合并,只需设置A列的字体ws.cell(row=row_idx, column=1).font = bold_font# 设置ASIN行(列标题)加粗for col_idx in range(3, len(transposed_df.columns) + 3): # 从第三列开始ws.cell(row=list(transposed_df.index).index("ASIN") + 1, column=col_idx).font = bold_font# 调整列宽ws.column_dimensions['A'].width = 8 # 合并列的一半ws.column_dimensions['B'].width = 8 # 合并列的一半# 对其他列设置固定宽度for idx in range(2, len(transposed_df.columns) + 2):col_letter = openpyxl.utils.get_column_letter(idx + 1) # +1 因为数据从第三列开始ws.column_dimensions[col_letter].width = 13# 添加图片到Excel - 处理"图片"行image_row_idx = list(transposed_df.index).index("图片") + 1 # +1 因为Excel行从1开始# 设置行高以容纳图片ws.row_dimensions[image_row_idx].height = 75 # 图片单元格行高为75# 设置品牌链接行高为45brand_link_row_idx = list(transposed_df.index).index("品牌链接") + 1ws.row_dimensions[brand_link_row_idx].height = 45# 添加"主要卖点对比"区域 - 在所有字段后面last_row_idx = len(transposed_df.index)start_selling_point_row = last_row_idx + 1 # 直接在原有内容下方,不空行# 只合并A列的单元格用于"主要卖点对比"标题selling_point_range = f'A{start_selling_point_row}:A{start_selling_point_row+3}'ws.merge_cells(selling_point_range)# 设置"主要卖点对比"标题selling_point_cell = ws.cell(row=start_selling_point_row, column=1)selling_point_cell.value = "主要卖点对比"selling_point_cell.font = Font(bold=True)selling_point_cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)# 为合并单元格的所有边添加边框# 注意:合并单元格的边框需要分别为每个被合并的单元格设置for row_idx in range(start_selling_point_row, start_selling_point_row + 4):cell = ws.cell(row=row_idx, column=1)cell.border = thin_border# 为B列和其他列添加对应的空白单元格并设置样式for col_idx in range(len(transposed_df.columns) + 1): # +1 包括B列col_pos = col_idx + 2 # 从第二列(B列)开始for row_offset in range(4): # 四行高度row_idx = start_selling_point_row + row_offsetcell = ws.cell(row=row_idx, column=col_pos)cell.value = "" # 空值cell.border = thin_border # 使用已定义的边框样式# 设置行高for row_offset in range(4):row_idx = start_selling_point_row + row_offsetws.row_dimensions[row_idx].height = 30 # 设置合适的行高# 在添加图片前,定义一个列表resized_img_paths = []# 为每个ASIN添加图片for col_idx, asin in enumerate(transposed_df.columns):# 查找对应的图片路径img_path = ""for row_data in result_data:if row_data['ASIN'] == asin and row_data['图片']:img_path = row_data['图片']breakif img_path and os.path.exists(img_path):try:# 计算图片应该放在哪一列,从第三列开始col_pos = col_idx + 3 # 第二列是字段名称,从第三列开始数据col_letter = openpyxl.utils.get_column_letter(col_pos)# 清除单元格中的文本值cell = ws.cell(row=image_row_idx, column=col_pos)cell.value = None# 强制生成100x100白底图片,内容居中max_size = (100, 100)pil_img = PILImage.open(img_path)pil_img.thumbnail(max_size, PILImage.LANCZOS) # 保持比例缩放到不超过100x100background = PILImage.new('RGB', max_size, (255, 255, 255))paste_x = (max_size[0] - pil_img.width) // 2paste_y = (max_size[1] - pil_img.height) // 2background.paste(pil_img, (paste_x, paste_y))# 使用唯一文件名避免冲突temp_img_id = str(uuid.uuid4())resized_img_path = f"temp_resized_{temp_img_id}.png"background.save(resized_img_path)# 添加图片到Excelimg = XLImage(resized_img_path)img.width = 100img.height = 100# 设置图片位置img_cell = f"{col_letter}{image_row_idx}"ws.add_image(img, img_cell)# 在for循环里,每次生成resized_img_path后resized_img_paths.append(resized_img_path)except Exception as e:pass # 忽略添加图片时的错误# 保存到内存中excel_buffer = io.BytesIO()wb.save(excel_buffer)excel_buffer.seek(0)# 在wb.save(excel_buffer)之后for path in resized_img_paths:if os.path.exists(path):os.remove(path)# 提供下载按钮st.download_button(14 unmodified lines1516171819202119 unmodified lines41424344454647484950515253545556575812 unmodified lines717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911029 unmodified lines14014114214314414514614714814915015115219 unmodified lines17217317417517617717817918018118218318413 unmodified lines19819920020120220320420520620720820921021 unmodified lines23223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027138 unmodified lines3103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923932 unmodified lines3963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324333 unmodified lines43743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247314 unmodified lines4884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395401 unmodified line54254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163214 unmodified linesfrom openpyxl.utils import get_column_letterfrom openpyxl.utils.cell import column_index_from_stringfrom openpyxl.utils.cell import coordinate_from_stringfrom collections import defaultdictst.set_page_config(page_title="竞品对比", layout="wide")19 unmodified linesif not os.path.exists(image_dir):os.makedirs(image_dir)def parse_key_value_pairs(text):"""解析键值对字符串,返回字典"""if pd.isna(text) or not isinstance(text, str): # 确保是字符串类型return {}pairs = [pair.strip() for pair in text.split("|")]result = {}for pair in pairs:if ":" in pair:key, value = pair.split(":", 1)result[key.strip()] = value.strip()return resultdef extract_images_from_excel(excel_file_path):"""从Excel文件中提取嵌入的图片"""# 创建临时目录12 unmodified lines# 加载Excel以获取ASIN列df = pd.read_excel(excel_file_path, engine='openpyxl')# ------------- BEGIN NEW CODE INTEGRATION: 解析详细参数 -------------detailed_param_keys = [] # 用于存储从'详细参数'提取的列名if '详细参数' in df.columns and not df['详细参数'].isna().all():st.write("正在解析 '详细参数' 列...")all_keys_set = set()parsed_data_list = []for text_entry in df['详细参数'].astype(str): # 确保处理的是字符串if pd.isna(text_entry) or text_entry.lower() == 'nan' or not text_entry.strip():parsed_pairs = {}else:parsed_pairs = parse_key_value_pairs(text_entry)parsed_data_list.append(parsed_pairs)all_keys_set.update(parsed_pairs.keys())detailed_param_keys = sorted(list(all_keys_set))if detailed_param_keys:temp_new_data = defaultdict(list)for parsed_pairs_item in parsed_data_list:for key_item in detailed_param_keys:temp_new_data[key_item].append(parsed_pairs_item.get(key_item, None))for key_item in detailed_param_keys:# 将解析出的列添加到df,如果列名已存在则覆盖df[key_item] = pd.Series(temp_new_data[key_item], index=df.index)st.success(f"成功从 '详细参数' 提取并更新/添加了 {len(detailed_param_keys)} 个列。")else:st.info("'详细参数' 列中未找到可解析的键值对数据。")elif '详细参数' not in df.columns:st.info("上传的文件中未找到 '详细参数' 列,跳过解析。")# ------------- END NEW CODE INTEGRATION -------------# 获取所有ASIN及其在DataFrame中的顺序asins = []for i, row in df.iterrows():29 unmodified linesif img_idx in image_files:img_path = image_files[img_idx]target_path = os.path.join(image_dir, f"{asin}.png")# 检查目标文件是否存在,如果存在则尝试删除或重命名if os.path.exists(target_path):try:os.remove(target_path)except OSError: # 文件可能被占用base, ext = os.path.splitext(target_path)target_path = f"{base}_{uuid.uuid4().hex[:6]}{ext}"shutil.copy2(img_path, target_path)asin_to_image[asin] = target_path19 unmodified linesif img_idx in image_files:img_path = image_files[img_idx]target_path = os.path.join(image_dir, f"{asin}.png")# 检查目标文件是否存在,如果存在则尝试删除或重命名if os.path.exists(target_path):try:os.remove(target_path)except OSError: # 文件可能被占用base, ext = os.path.splitext(target_path)target_path = f"{base}_{uuid.uuid4().hex[:6]}{ext}"shutil.copy2(img_path, target_path)asin_to_image[asin] = target_pathexcept Exception as e:13 unmodified linesimg_idx = sorted_img_indices[i]img_path = image_files[img_idx]target_path = os.path.join(image_dir, f"{asin}.png")# 检查目标文件是否存在if os.path.exists(target_path):try:os.remove(target_path)except OSError:base, ext = os.path.splitext(target_path)target_path = f"{base}_{uuid.uuid4().hex[:6]}{ext}"shutil.copy2(img_path, target_path)asin_to_image[asin] = target_path21 unmodified lines# 读取Excel文件df = pd.read_excel(temp_file, engine='openpyxl')# ------------- BEGIN NEW CODE INTEGRATION: 解析详细参数 -------------detailed_param_keys = [] # 用于存储从'详细参数'提取的列名if '详细参数' in df.columns and not df['详细参数'].isna().all():st.write("正在解析 '详细参数' 列...")all_keys_set = set()parsed_data_list = []for text_entry in df['详细参数'].astype(str): # 确保处理的是字符串if pd.isna(text_entry) or text_entry.lower() == 'nan' or not text_entry.strip():parsed_pairs = {}else:parsed_pairs = parse_key_value_pairs(text_entry)parsed_data_list.append(parsed_pairs)all_keys_set.update(parsed_pairs.keys())detailed_param_keys = sorted(list(all_keys_set))if detailed_param_keys:temp_new_data = defaultdict(list)for parsed_pairs_item in parsed_data_list:for key_item in detailed_param_keys:temp_new_data[key_item].append(parsed_pairs_item.get(key_item, None))for key_item in detailed_param_keys:# 将解析出的列添加到df,如果列名已存在则覆盖df[key_item] = pd.Series(temp_new_data[key_item], index=df.index)st.success(f"成功从 '详细参数' 提取并更新/添加了 {len(detailed_param_keys)} 个列。")else:st.info("'详细参数' 列中未找到可解析的键值对数据。")elif '详细参数' not in df.columns:st.info("上传的文件中未找到 '详细参数' 列,跳过解析。")# ------------- END NEW CODE INTEGRATION -------------# 提取所有ASIN值asins = df['ASIN'].dropna().unique().tolist()38 unmodified lines# 过滤选中的ASIN数据filtered_df = df[df['ASIN'].isin(final_selected_asins)]# ------------- BEGIN FILTERING EMPTY DETAILED PARAMETERS FOR SELECTED ASINS -------------if detailed_param_keys and not filtered_df.empty:st.write(f"初步找到 {len(detailed_param_keys)} 个详细参数键。正在检查所选ASIN中的空值...")non_empty_detailed_param_keys_for_selected = []removed_keys_count = 0for dp_key in detailed_param_keys:if dp_key in filtered_df.columns: # Key must exist in the filtered dataframe columnsis_empty_for_all_selected = True# Check all values for this key in the filtered_dffor value_in_filtered_df in filtered_df[dp_key]:if not (pd.isna(value_in_filtered_df) or str(value_in_filtered_df).strip() == ""):is_empty_for_all_selected = Falsebreak # Found a non-empty value, so this key is keptif not is_empty_for_all_selected:non_empty_detailed_param_keys_for_selected.append(dp_key)else:# st.write(f"详细参数 \'{dp_key}\' 在所有选定ASIN中均为空,将不被包含在结果中。")removed_keys_count += 1# If dp_key is not in filtered_df.columns, it means it wasn't relevant or couldn't be processed earlier.# It won't be included by default as subsequent logic relies on columns in filtered_df.if removed_keys_count > 0:st.info(f"已移除 {removed_keys_count} 个在所选ASIN中值全为空的详细参数。")detailed_param_keys = non_empty_detailed_param_keys_for_selected # Update the listelif detailed_param_keys and filtered_df.empty:st.warning("没有选择任何有效的ASIN,或所选ASIN无数据,无法过滤详细参数。")# ------------- END FILTERING EMPTY DETAILED PARAMETERS -------------# 创建一个空列表用于存储结果数据result_data = []# 定义基础列名 (这些是代码中特别处理的列)base_columns = ["图片", "品牌", "品牌链接", "卖家所属地", "ASIN", "大类排名", "小类排名","近30天月销量", "近30天月销售额", "价格", "变体", "RV数量", "RV评分","上架时间", "重量(g)", "尺寸(cm)"]# 合并基础列和从'详细参数'提取的列,确保唯一性并保持顺序final_display_columns = base_columns[:]for key in detailed_param_keys:if key not in final_display_columns:final_display_columns.append(key)# 处理每个选中的ASINfor i, (idx, row) in enumerate(filtered_df.iterrows()):current_asin_val = row.get("ASIN", "") # Get raw ASIN valueif not isinstance(current_asin_val, str): # Ensure ASIN is stringcurrent_asin_val = str(current_asin_val)# 创建新行数据new_row = {}# 检查是否有对应的图片if current_asin_val in asin_to_image:new_row["图片"] = asin_to_image[current_asin_val]else:new_row["图片"] = "" # 图片为空字符串# Helper function to get string value or empty if None/NaNdef get_value_as_str_or_empty(r, k):v = r.get(k)return "" if pd.isna(v) else str(v)new_row["品牌"] = get_value_as_str_or_empty(row, "品牌")new_row["品牌链接"] = get_value_as_str_or_empty(row, "品牌链接")new_row["卖家所属地"] = get_value_as_str_or_empty(row, "卖家所属地")new_row["ASIN"] = current_asin_val # Already processed ASINnew_row["大类排名"] = get_value_as_str_or_empty(row, "大类BSR")new_row["小类排名"] = get_value_as_str_or_empty(row, "小类BSR")new_row["近30天月销量"] = get_value_as_str_or_empty(row, "月销量")# 处理月销售额 - 匹配开头monthly_sales_found = Falsefor col in df.columns: # 使用更新后的df.columnsif "月销售额" in col:val_ms = row.get(col)new_row["近30天月销售额"] = "" if pd.isna(val_ms) else str(val_ms)monthly_sales_found = Truebreak2 unmodified lines# 处理价格 - 匹配开头price_found = Falsefor col in df.columns: # 使用更新后的df.columnsif "价格" in col:val_price = row.get(col)new_row["价格"] = "" if pd.isna(val_price) else str(val_price)price_found = Truebreakif not price_found:new_row["价格"] = ""new_row["变体"] = get_value_as_str_or_empty(row, "变体数")new_row["RV数量"] = get_value_as_str_or_empty(row, "评分数")new_row["RV评分"] = get_value_as_str_or_empty(row, "评分")new_row["上架时间"] = get_value_as_str_or_empty(row, "上架时间")# 处理重量 - 优先查找"重量.1"列,其次查找包含g的值weight_found = False# 优先查找"重量.1"列if "重量.1" in df.columns: # 使用更新后的df.columnsraw_weight_1 = row.get("重量.1")value_w1 = "" if pd.isna(raw_weight_1) else str(raw_weight_1).strip()if value_w1: # Check if non-empty after stripnew_row["重量(g)"] = value_w1weight_found = True# 如果没找到,再查找所有包含"重量"且以g结尾的列if not weight_found:for col in df.columns: # 使用更新后的df.columnsif "重量" in col:raw_weight_col = row.get(col)value_wc = "" if pd.isna(raw_weight_col) else str(raw_weight_col).strip()if value_wc.lower().endswith("g"):new_row["重量(g)"] = value_wcweight_found = Truebreakif not weight_found:3 unmodified linessize_found = False# 首先检查"体积.1"列if "体积.1" in df.columns: # 使用更新后的df.columnsraw_size_1 = row.get("体积.1")value_s1 = "" if pd.isna(raw_size_1) else str(raw_size_1).strip()if value_s1: # Check if non-empty after stripnew_row["尺寸(cm)"] = value_s1size_found = True# 如果没找到,再搜索其他可能包含尺寸的列if not size_found:for col in df.columns: # 使用更新后的df.columnsif any(term in col for term in ["尺寸", "体积"]):raw_size_col = row.get(col)value_sc = "" if pd.isna(raw_size_col) else str(raw_size_col).strip()if "cm" in value_sc.lower() or " x " in value_sc.lower():new_row["尺寸(cm)"] = value_scsize_found = Truebreakif not size_found:new_row["尺寸(cm)"] = ""# 添加从\'详细参数\'提取的列到new_rowfor key in detailed_param_keys:val_dp = row.get(key)new_row[key] = "" if pd.isna(val_dp) else str(val_dp)# 将新行添加到结果列表result_data.append(new_row)# 创建结果DataFrame,使用final_display_columns确保包含新列且顺序正确result_df = pd.DataFrame(result_data, columns=final_display_columns)# 显示结果表格 - 使用转换为字符串的方式避免Arrow错误st.subheader("提取结果")14 unmodified linesws = wb.activews.title = "提取结果"# --- BEGIN MODIFIED HEADER AND FIELD NAME WRITING ---all_fields_in_transposed_df = transposed_df.index.tolist()first_detailed_key_processed = Falsecurrent_excel_row_for_styling = 1for field_name in all_fields_in_transposed_df:if field_name not in detailed_param_keys:# Standard fieldws.merge_cells(start_row=current_excel_row_for_styling, start_column=1, end_row=current_excel_row_for_styling, end_column=2) # Merge A:Bcell_to_style = ws.cell(row=current_excel_row_for_styling, column=1, value=field_name)cell_to_style.font = Font(bold=True) # Standard fields are boldcurrent_excel_row_for_styling += 1else:# Detailed parameter keyif not first_detailed_key_processed:start_dp_excel_row = current_excel_row_for_stylingnum_dp_keys = len(detailed_param_keys)# Ensure detailed_param_keys are contiguous as expectedactual_dp_keys_in_order = [f for f in all_fields_in_transposed_df if f in detailed_param_keys]if len(actual_dp_keys_in_order) == num_dp_keys : # basic checkend_dp_excel_row = start_dp_excel_row + num_dp_keys - 1ws.merge_cells(start_row=start_dp_excel_row, start_column=1, end_row=end_dp_excel_row, end_column=1) # Merge A column onlytitle_cell = ws.cell(row=start_dp_excel_row, column=1, value="详细参数")title_cell.font = Font(bold=True)title_cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)first_detailed_key_processed = True# Write the actual detailed parameter key in column Bws.cell(row=current_excel_row_for_styling, column=2, value=field_name)ws.row_dimensions[current_excel_row_for_styling].height = 25 # Set height for detailed param rowscurrent_excel_row_for_styling += 1# --- END MODIFIED HEADER AND FIELD NAME WRITING ---# 写入数据 - 每个ASIN一列,从第三列开始for col_idx, asin in enumerate(transposed_df.columns):col_pos = col_idx + 3 # 数据从第三列(C列)开始for row_idx, field in enumerate(transposed_df.index):excel_row_for_data = row_idx + 1if field == "图片":continue # 图片处理在后面单独进行cell = ws.cell(row=excel_row_for_data, column=col_pos)cell.value = str(transposed_df.loc[field, asin])# 设置单元格样式 (全局边框和居中)thin_border = Border(left=Side(style='thin'),right=Side(style='thin'),1 unmodified linebottom=Side(style='thin'))center_aligned = Alignment(horizontal='center', vertical='center', wrap_text=True)# 遍历所有相关单元格设置边框和居中对齐# Max row is determined by the number of fields in transposed_dfmax_row_to_style = len(transposed_df.index)# Max col is ASINs + 2 (for A and B columns)max_col_to_style = len(transposed_df.columns) + 2for r_idx in range(1, max_row_to_style + 1):for c_idx in range(1, max_col_to_style + 1):cell = ws.cell(row=r_idx, column=c_idx)cell.border = thin_border# Apply general center alignment, specific cells can overrideif not (c_idx == 1 and ws.cell(row=r_idx, column=c_idx).value == "详细参数"): # Avoid double-setting for merged titlecell.alignment = center_aligned# Specific styling for "详细参数" title already done (bold, alignment)# Standard field names in A:B are already bolded# 设置ASIN行(列标题, 即ASIN值本身在数据中的行)加粗# This logic needs to find the row where field name is "ASIN"if "ASIN" in transposed_df.index:asin_header_row_excel = transposed_df.index.tolist().index("ASIN") + 1for c_idx in range(3, max_col_to_style + 1): # ASIN values start from column Cws.cell(row=asin_header_row_excel, column=c_idx).font = Font(bold=True)# 调整列宽ws.column_dimensions['A'].width = 10ws.column_dimensions['B'].width = 13 # For detailed parameter keysfor idx_cw in range(len(transposed_df.columns)):col_letter = openpyxl.utils.get_column_letter(idx_cw + 3) # Data columns C, D, ...ws.column_dimensions[col_letter].width = 13# 添加图片到Excel - 处理"图片"行 (This logic should remain largely the same)if "图片" in transposed_df.index:image_row_idx_excel = transposed_df.index.tolist().index("图片") + 1ws.row_dimensions[image_row_idx_excel].height = 75# 设置品牌链接行高为45if "品牌链接" in transposed_df.index:brand_link_row_idx_excel = transposed_df.index.tolist().index("品牌链接") + 1ws.row_dimensions[brand_link_row_idx_excel].height = 45resized_img_paths = []for col_idx, asin_val in enumerate(transposed_df.columns):img_path_val = transposed_df.loc["图片", asin_val]if img_path_val and isinstance(img_path_val, str) and os.path.exists(img_path_val):try:col_pos_img = col_idx + 3col_letter_img = openpyxl.utils.get_column_letter(col_pos_img)cell_img_text = ws.cell(row=image_row_idx_excel, column=col_pos_img)cell_img_text.value = None # Clear any textmax_size = (100, 100)pil_img = PILImage.open(img_path_val)pil_img.thumbnail(max_size, PILImage.LANCZOS)background = PILImage.new('RGB', max_size, (255, 255, 255))paste_x = (max_size[0] - pil_img.width) // 2paste_y = (max_size[1] - pil_img.height) // 2background.paste(pil_img, (paste_x, paste_y))temp_img_id = str(uuid.uuid4())resized_img_path = f"temp_resized_{temp_img_id}.png"background.save(resized_img_path)resized_img_paths.append(resized_img_path)img_xl = XLImage(resized_img_path)img_xl.width = 100img_xl.height = 100ws.add_image(img_xl, f"{col_letter_img}{image_row_idx_excel}")except Exception as e_img:pass # Ignore image adding errors# Image cleanup loop will be at the end# 保存到内存中excel_buffer = io.BytesIO()wb.save(excel_buffer)excel_buffer.seek(0)# 在wb.save(excel_buffer)之后清理临时图片if "resized_img_paths" in locals():for path in resized_img_paths:if os.path.exists(path):os.remove(path)# 提供下载按钮st.download_button(
app.py+310-170