Update app.py
Browse files11 unmodified lines12131415161718192021222324252627282930313233343536373816 unmodified lines55565758596061626 unmodified lines6970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956011 unmodified linesst.set_page_config(page_title="细分市场", layout="wide")st.title("细分市场分析")# 添加更详细的提示信息st.write("""### 文件要求- 请上传包含产品细分市场数据的Excel文件(.xlsx格式)(请使用卖家精灵导出的Top数据,自行分类)- 文件中应包含带有"分类"字样的列(用于区分不同的产品类别)- 文件中应包含"月销量"、"月销售额"、"价格"、"评分数"数据列- 文件中应包含"图片"列(用于提取产品图片)- 文件中包含"上架时间"列### 应用功能本应用将自动:1. 识别并提取各个产品分类2. 计算每个分类的销量、销售额、ASIN数等数据3. 计算各类别占比和平均值4. 提取并展示每个分类的代表性图片5. 生成汇总报表供下载""")uploaded_file = st.file_uploader("选择一个XLSX文件", type="xlsx")@st.cache_datadef read_excel_data(file_bytes, sheet_name=None):16 unmodified lines# 获取工作表列表(使用缓存)sheet_names = get_excel_sheets(data)# 让用户选择要处理的sheetsheet_name = st.selectbox("请选择要处理的Sheet", sheet_names)# 读取选定的sheet(使用缓存)df = read_excel_data(data, sheet_name=sheet_name)6 unmodified linesst.subheader("原始数据预览")st.dataframe(df.head(10))# 提取分类字段if st.button("处理数据"):# 找到所有分类categories = []for col in df.columns:if isinstance(col, str) and "分类" in col:unique_categories = df[col].dropna().unique().tolist()categories.extend(unique_categories)# 去除重复的分类categories = list(dict.fromkeys(categories))# 存储每个分类的图片category_images = {category: [] for category in categories}# 找到图片列的索引image_col_indices = []for col_idx, col_name in enumerate(df.columns):if isinstance(col_name, str) and ("图片" in col_name or "产品图" in col_name or "主图" in col_name):image_col_indices.append(col_idx)# 提取嵌入在Excel中的图片embedded_images = {}for image in ws._images:row = image.anchor._from.rowcol = image.anchor._from.colif col in image_col_indices and row > 0: # 跳过标题行# 获取该行的分类row_data = df.iloc[row-1] # 因为Excel行号从1开始,pandas从0开始# 查找该行的分类for cat_col in df.columns:if isinstance(cat_col, str) and "分类" in cat_col and pd.notna(row_data[cat_col]):category = row_data[cat_col]if category in categories:# 将图片对象添加到对应分类category_images[category].append(image)# 在网页上展示随机选择的分类图片st.subheader("各分类随机图片展示")image_cols = st.columns(len(categories))# 存储用于导出的图片对象export_images = {}for i, category in enumerate(categories):if category_images[category]:# 从该分类的图片中随机选择一个random_image_idx = np.random.randint(0, len(category_images[category]))random_image = category_images[category][random_image_idx]# 使用NamedTemporaryFile安全地创建临时文件with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as tmp_file:# 获取图片数据并保存为文件img_data = random_image._data()tmp_file.write(img_data)tmp_path = tmp_file.nametry:# 在Streamlit界��上显示图片with image_cols[i]:st.write(f"**{category}**")try:img = PILImage.open(tmp_path)st.image(img, caption=category, use_container_width=True)except Exception as e:st.error(f"无法显示{category}图片: {str(e)}")except Exception as e:with image_cols[i]:st.write(f"**{category}**")st.error(f"图片处理错误: {str(e)}")finally:# 清理临时文件if os.path.exists(tmp_path):try:os.unlink(tmp_path)except:pass# 存储图片数据用于Excel导出(而非对象引用)export_images[category] = img_dataelse:with image_cols[i]:st.write(f"**{category}**")st.info(f"没有找到{category}的图片")# 创建新的DataFrame用于结果result_df = pd.DataFrame()# 第一行:款式result_df.loc[0, "A"] = "款式"for i, category in enumerate(categories):result_df.loc[0, chr(66 + i)] = categoryresult_df.loc[0, chr(66 + len(categories))] = "总计"# 第二行:图片result_df.loc[1, "A"] = "图片"# 第三行:月销量result_df.loc[2, "A"] = "月销量"# 第四行:月销售额result_df.loc[3, "A"] = "月销售额"# 第五行:平均月销售额result_df.loc[4, "A"] = "平均月销售额"# 第六行:ASIN数result_df.loc[5, "A"] = "ASIN数"# 第七行:平均价格result_df.loc[6, "A"] = "平均价格"# 第八行:平均reviewresult_df.loc[7, "A"] = "平均review"# 第九行:月销量占比result_df.loc[8, "A"] = "月销量占比"# 第十行:月销售额占比result_df.loc[9, "A"] = "月销售额占比"# 第十一行:ASIN占比result_df.loc[10, "A"] = "ASIN占比"# 第十二行:半年新品数量result_df.loc[11, "A"] = "半年新品数量"# 第十三行:半年新品占比result_df.loc[12, "A"] = "半年新品占比"# 获取当前日期current_date = datetime.now()# 计算半年前的日期half_year_ago = current_date - timedelta(days=180)# 用于存储每个分类的统计数据category_stats = {}for category in categories:category_stats[category] = {'sales_volume': 0, # 月销量'sales_amount': 0, # 月销售额'asin_count': 0, # ASIN数'price_sum': 0, # 价格总和'review_sum': 0, # 评分总和'new_product_count': 0 # 半年新品数量}# 计算每个分类的统计数据for col in df.columns:if isinstance(col, str) and "分类" in col:# 处理每个分类列for category in categories:# 找到对应分类的行category_rows = df[df[col] == category]# 计算ASIN数(该分类下的行数)category_stats[category]['asin_count'] += len(category_rows)# 计算半年新品数量for _, row in category_rows.iterrows():# 查找上架时间列for col_name in row.index:if isinstance(col_name, str) and ("上架时间" in col_name or "上架日期" in col_name):try:# 尝试将上架时间转换为日期对象if pd.notna(row[col_name]):listing_date = pd.to_datetime(row[col_name])# 如果上架时间在半年内,则计为新品if listing_date > half_year_ago:category_stats[category]['new_product_count'] += 1breakexcept:# 如果转换失败,则忽略该行pass# 查找月销量和月销售额列for sales_col in df.columns:if isinstance(sales_col, str):if sales_col == "月销量" or (isinstance(sales_col, str) and sales_col.strip() == "月销量"):# 累加月销量(确保为整数)category_stats[category]['sales_volume'] += int(category_rows[sales_col].sum())elif sales_col.startswith("月销售额"):# 累加月销售额category_stats[category]['sales_amount'] += category_rows[sales_col].sum()elif sales_col.startswith("价格"):# 累加价格category_stats[category]['price_sum'] += category_rows[sales_col].sum()elif sales_col.startswith("评分数"):# 累加评分数category_stats[category]['review_sum'] += category_rows[sales_col].sum()# 计算总计total_sales_volume = 0total_sales_amount = 0total_asin_count = 0total_price_sum = 0total_review_sum = 0# 为每个分类随机选择一个图片for i, category in enumerate(categories):if category_images[category]:# 从该分类的图片中随机选择一个random_image_idx = np.random.randint(0, len(category_images[category]))random_image = category_images[category][random_image_idx]# 填充结果DataFramefor i, category in enumerate(categories):# 获取该分类的统计数据stats = category_stats[category]# 月销量(确保为整数)sales_volume = int(stats['sales_volume'])result_df.loc[2, chr(66 + i)] = sales_volumetotal_sales_volume += sales_volume# 月销售额sales_amount = stats['sales_amount']result_df.loc[3, chr(66 + i)] = sales_amounttotal_sales_amount += sales_amount# ASIN数asin_count = stats['asin_count']result_df.loc[5, chr(66 + i)] = asin_counttotal_asin_count += asin_count# 平均月销售额 = 月销售额 / ASIN数avg_sales_amount = sales_amount / asin_count if asin_count > 0 else 0result_df.loc[4, chr(66 + i)] = avg_sales_amount# 平均价格 = 价格总和 / ASIN数price_sum = stats['price_sum']avg_price = price_sum / asin_count if asin_count > 0 else 0result_df.loc[6, chr(66 + i)] = avg_pricetotal_price_sum += price_sum# 平均review = 评分总和 / ASIN数review_sum = stats['review_sum']avg_review = review_sum / asin_count if asin_count > 0 else 0result_df.loc[7, chr(66 + i)] = avg_reviewtotal_review_sum += review_sum# 添加总计列result_df.loc[2, chr(66 + len(categories))] = int(total_sales_volume) # 月销量总计(确保为整数)result_df.loc[3, chr(66 + len(categories))] = total_sales_amount # 月销售额总计result_df.loc[5, chr(66 + len(categories))] = total_asin_count # ASIN数总计# 总体平均月销售额 = 总月销售额 / 总ASIN数total_avg_sales_amount = total_sales_amount / total_asin_count if total_asin_count > 0 else 0result_df.loc[4, chr(66 + len(categories))] = total_avg_sales_amount# 总体平均价格 = 总价格总和 / 总ASIN数total_avg_price = total_price_sum / total_asin_count if total_asin_count > 0 else 0result_df.loc[6, chr(66 + len(categories))] = total_avg_price# 总体平均review = 总review总和 / 总ASIN数total_avg_review = total_review_sum / total_asin_count if total_asin_count > 0 else 0result_df.loc[7, chr(66 + len(categories))] = total_avg_review# 计算月销量占比和月销售额占比for i, category in enumerate(categories):# 月销量占比sales_volume = int(result_df.loc[2, chr(66 + i)]) # 确保为整数sales_volume_percentage = (sales_volume / total_sales_volume * 100) if total_sales_volume > 0 else 0result_df.loc[8, chr(66 + i)] = sales_volume_percentage# 月销售额占比sales_amount = float(result_df.loc[3, chr(66 + i)])sales_amount_percentage = (sales_amount / total_sales_amount * 100) if total_sales_amount > 0 else 0result_df.loc[9, chr(66 + i)] = sales_amount_percentage# 计算半年新品总数total_new_product_count = 0for category in categories:new_product_count = category_stats[category]['new_product_count']result_df.loc[11, chr(66 + categories.index(category))] = new_product_counttotal_new_product_count += new_product_count# 添加半年新品总数到总计列result_df.loc[11, chr(66 + len(categories))] = total_new_product_count# 计算ASIN占比for i, category in enumerate(categories):asin_count = float(result_df.loc[5, chr(66 + i)])asin_percentage = (asin_count / total_asin_count * 100) if total_asin_count > 0 else 0result_df.loc[10, chr(66 + i)] = asin_percentage# 计算半年新品占比for i, category in enumerate(categories):new_product_count = float(result_df.loc[11, chr(66 + i)])new_product_percentage = (new_product_count / total_new_product_count * 100) if total_new_product_count > 0 else 0result_df.loc[12, chr(66 + i)] = new_product_percentage# 总计列的占比都是100%result_df.loc[8, chr(66 + len(categories))] = 100 # 月销量占比result_df.loc[9, chr(66 + len(categories))] = 100 # 月销售额占比result_df.loc[10, chr(66 + len(categories))] = 100 # ASIN占比result_df.loc[12, chr(66 + len(categories))] = 100 # 半年新品占比# 将数据框转换为字符串类型以避免Arrow兼容性问题# 但先保存一个数值版本用于Excel导出result_df_numeric = result_df.copy()# 显示结果(转换为字符串以避免Arrow兼容性问题)st.subheader("处理后的数据")# 格式化数值显示display_df = result_df.copy()for i in range(2, 13): # 处理第3-13行(索引2-12)的数值格式for j in range(1, len(categories) + 2): # B列到最后一列col = chr(65 + j)if i in [4, 6, 7]: # 平均月销售额、平均价格、平均review保留2位小数try:display_df.loc[i, col] = f"{float(display_df.loc[i, col]):.2f}"except:passelif i in [8, 9, 10, 12]: # 月销量占比、月销售额占比、ASIN占比、半年新品占比保留2位小数并添加%符号try:display_df.loc[i, col] = f"{float(display_df.loc[i, col]):.2f}%"except:passelif i in [2, 3, 5, 11]: # 销量、销售额、ASIN数、半年新品数量使用千分位分隔符try:display_df.loc[i, col] = f"{int(float(display_df.loc[i, col])):,}"except:passst.dataframe(display_df)# 提供下载功能# 创建一个新的BytesIO对象output = io.BytesIO()# 预处理所有数据export_df = result_df_numeric.copy()# 1. 预处理百分比数据for i in [8, 9, 10, 12]: # 月销量占比、月销售额占比、ASIN占比、半年新品占比for j in range(1, len(categories) + 2):col = chr(65 + j)try:cell_value = export_df.loc[i, col]if pd.notna(cell_value):# 将百分比值除以100转换为小数export_df.loc[i, col] = float(cell_value) / 100except:pass# 2. 处理小数值(平均月销售额、平均价格、平均review)for i in [4, 6, 7]: # 平均月销售额、平均价格、平均reviewfor j in range(1, len(categories) + 2):col = chr(65 + j)try:cell_value = export_df.loc[i, col]if pd.notna(cell_value):# 将小数值四舍五入为两位小数export_df.loc[i, col] = round(float(cell_value), 2)except:pass# 3. 处理销售额(保留两位小数)for j in range(1, len(categories) + 2):col = chr(65 + j)try:cell_value = export_df.loc[3, col] # 月销售额在第4行(索引3)if pd.notna(cell_value):export_df.loc[3, col] = round(float(cell_value), 2)except:pass# 写入Excelwith pd.ExcelWriter(output, engine='openpyxl') as writer:# 直接写入数据,不包含表头export_df.to_excel(writer, sheet_name="汇总结果", index=False, header=False)# 获取工作表workbook = writer.bookworksheet = writer.sheets["汇总结果"]# 设置图片行的高度为150worksheet.row_dimensions[2].height = 150# 设置A列宽度为15worksheet.column_dimensions['A'].width = 15# 设置所有分类列的宽度为25for i in range(len(categories) + 1):col_letter = chr(66 + i) # B, C, D...worksheet.column_dimensions[col_letter].width = 25 # Excel列宽单位约为7像素# 将已经在网页上显示的随机图片添加到工作表中for i, category in enumerate(categories):if category in export_images:# 使用之前选择的随机图片,但重新创建新的Image对象img_data = export_images[category]img_cell = chr(66 + i) + "2" # B2, C2, D2...等单元格# 重新创建XLImage对象而不是直接使用原来的new_img = XLImage(io.BytesIO(img_data))worksheet.add_image(new_img, img_cell)# 导入所需的样式模块from openpyxl.styles import numbers, Font, Border, Side, Alignment# 定义边框样式 - 实线边框thin_border = Border(left=Side(style='thin'),right=Side(style='thin'),top=Side(style='thin'),bottom=Side(style='thin'))# 定义粗体字体bold_font = Font(bold=True)# 对A列标题加粗for i in range(13): # 假设有13行数据cell = worksheet.cell(row=i+1, column=1) # A列cell.font = bold_font# 为所有单元格添加边框# 获取工作表的最大行和列max_row = 13 # 根据您的数据结构,可能需要调整max_col = len(categories) + 2 # A列 + 所有分类列 + 总计列for row in range(1, max_row + 1):for col in range(1, max_col + 1):cell = worksheet.cell(row=row, column=col)cell.border = thin_border# 对所有数值应用格式# 1. 对百分比列应用格式for i in [8, 9, 10, 12]: # 月销量占比、月销售额占比、ASIN占比、半年新品占比for j in range(1, len(categories) + 2):# 计算单元格位置(不考虑标题行)cell = worksheet.cell(row=i+1, column=j+1) # +1是因为没有标题行,只考虑索引从0开始# 设置为百分比格式cell.number_format = '0.00%'# 2. 对小数值应用格式(平均月销售额、平均价格、平均review)for i in [4, 6, 7]: # 平均月销售额、平均价格、平均reviewfor j in range(1, len(categories) + 2):cell = worksheet.cell(row=i+1, column=j+1)cell.number_format = '0.00'# 3. 对整数值应用千分位格式(月销量、月销售额、ASIN数、半年新品数量)for i in [2, 3, 5, 11]: # 销量、销售额、ASIN数、半年新品数量for j in range(1, len(categories) + 2):cell = worksheet.cell(row=i+1, column=j+1)# 对于销售额(i=3),设置为带两位小数的千分位格式if i == 3:cell.number_format = '#,##0.00'else:cell.number_format = '#,##0'# 确保output已经被正确写入并准备好读取output.seek(0)# 使用download_button提供下载功能st.download_button(label="下载处理后的Excel文件",data=output,file_name="处理后的数据.xlsx",mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")if uploaded_file is not None:process_excel(uploaded_file)else:st.info("请上传一个Excel文件")# 添加使用说明with st.expander("使用说明"):st.markdown("""## 使用说明1. 上传包含数据的Excel文件(.xlsx格式)2. 选择要处理的工作表3. 点击"处理数据"按钮4. 查看处理结果5. 下载处理结果的Excel文件### 数据要求- Excel文件中应包含带有"分类"关键词的列- Excel文件中应包含带有"月销量"关键词的列- 如果需要计算半年新品,文件中应包含"上架时间"或"上架日期"列### 输出说明- 导出的Excel文件直接以"款式"作为第一行- 第二行:以"图片"开头,其余留空- 第三行:以"月销量"开头,包含每个分类的月销量总和,最后是所有分类月销量的总计""")11 unmodified lines12131415161718192021222324252627282930313233343536373816 unmodified lines5556575859606162636 unmodified lines70717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653711 unmodified linesst.set_page_config(page_title="细分市场", layout="wide")st.title("🪆 细分市场分析")st.markdown("""上传卖家精灵数据+“分类”数据,自动得出不同产品分类的月销量等数据对比(如下载结果示例)""")# 添加下载按钮st.link_button("📥 数据源示例","http://objects.mambate.top/example/细分市场数据源示例.xlsx",help="点击下载数据源示例文件")st.link_button("📊 下载结果示例","http://objects.mambate.top/example/细分市场结果.xlsx",help="点击下载结果示例文件")st.markdown("""源数据为卖家精灵+“分类”数据(需要新增一列字段名为“分类”的数据)""")uploaded_file = st.file_uploader("上传数据源xlsx文件", type="xlsx")@st.cache_datadef read_excel_data(file_bytes, sheet_name=None):16 unmodified lines# 获取工作表列表(使用缓存)sheet_names = get_excel_sheets(data)# 默认使用第一个工作簿sheet_name = sheet_names[0]st.info(f"正在处理工作簿: {sheet_name}")# 读取选定的sheet(使用缓存)df = read_excel_data(data, sheet_name=sheet_name)6 unmodified linesst.subheader("原始数据预览")st.dataframe(df.head(10))# 找到所有分类categories = []for col in df.columns:if isinstance(col, str) and "分类" in col:unique_categories = df[col].dropna().unique().tolist()categories.extend(unique_categories)# 去除重复的分类categories = list(dict.fromkeys(categories))# 存储每个分类的图片category_images = {category: [] for category in categories}# 找到图片列的索引image_col_indices = []for col_idx, col_name in enumerate(df.columns):if isinstance(col_name, str) and ("图片" in col_name or "产品图" in col_name or "主图" in col_name):image_col_indices.append(col_idx)# 提取嵌入在Excel中的图片embedded_images = {}for image in ws._images:row = image.anchor._from.rowcol = image.anchor._from.colif col in image_col_indices and row > 0: # 跳过标题行# 获取该行的分类row_data = df.iloc[row-1] # 因为Excel行号从1开始,pandas从0开始# 查找该行的分类for cat_col in df.columns:if isinstance(cat_col, str) and "分类" in cat_col and pd.notna(row_data[cat_col]):category = row_data[cat_col]if category in categories:# 将图片对象添加到对应分类category_images[category].append(image)# 在网页上展示随机选择的分类图片st.subheader("各分类随机图片展示")image_cols = st.columns(len(categories))# 存储用于导出的图片对象export_images = {}for i, category in enumerate(categories):if category_images[category]:# 从该分类的图片中随机选择一个random_image_idx = np.random.randint(0, len(category_images[category]))random_image = category_images[category][random_image_idx]# 使用NamedTemporaryFile安全地创建临时文件with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as tmp_file:# 获取图片数据并保存为文件img_data = random_image._data()tmp_file.write(img_data)tmp_path = tmp_file.nametry:# 在Streamlit界面上显示图片with image_cols[i]:st.write(f"**{category}**")try:img = PILImage.open(tmp_path)st.image(img, caption=category, use_container_width=True)except Exception as e:st.error(f"无法显示{category}图片: {str(e)}")except Exception as e:with image_cols[i]:st.write(f"**{category}**")st.error(f"图片处理错误: {str(e)}")finally:# 清理临时文件if os.path.exists(tmp_path):try:os.unlink(tmp_path)except:pass# 存储图片数据用于Excel导出(而非对象引用)export_images[category] = img_dataelse:with image_cols[i]:st.write(f"**{category}**")st.info(f"没有找到{category}的图片")# 创建新的DataFrame用于结果result_df = pd.DataFrame()# 第一行:款式result_df.loc[0, "A"] = "款式"for i, category in enumerate(categories):result_df.loc[0, chr(66 + i)] = categoryresult_df.loc[0, chr(66 + len(categories))] = "总计"# 第二行:图片result_df.loc[1, "A"] = "图片"# 第三行:月销量result_df.loc[2, "A"] = "月销量"# 第四行:月销售额result_df.loc[3, "A"] = "月销售额"# 第五行:平均月销售额result_df.loc[4, "A"] = "平均月销售额"# 第六行:ASIN数result_df.loc[5, "A"] = "ASIN数"# 第七行:平均价格result_df.loc[6, "A"] = "平均价格"# 第八行:平均reviewresult_df.loc[7, "A"] = "平均review"# 第九行:月销量占比result_df.loc[8, "A"] = "月销量占比"# 第十行:月销售额占比result_df.loc[9, "A"] = "月销售额占比"# 第十一行:ASIN占比result_df.loc[10, "A"] = "ASIN占比"# 第十二行:半年新品数量result_df.loc[11, "A"] = "半年新品数量"# 第十三行:半年新品占比result_df.loc[12, "A"] = "半年新品占比"# 获取当前日期current_date = datetime.now()# 计算半年前的日期half_year_ago = current_date - timedelta(days=180)# 用于存储每个分类的统计数据category_stats = {}for category in categories:category_stats[category] = {'sales_volume': 0, # 月销量'sales_amount': 0, # 月销售额'asin_count': 0, # ASIN数'price_sum': 0, # 价格总和'review_sum': 0, # 评分总和'new_product_count': 0 # 半年新品数量}# 计算每个分类的统计数据for col in df.columns:if isinstance(col, str) and "分类" in col:# 处理每个分类列for category in categories:# 找到对应分类的行category_rows = df[df[col] == category]# 计算ASIN数(该分类下的行数)category_stats[category]['asin_count'] += len(category_rows)# 计算半年新品数量for _, row in category_rows.iterrows():# 查找上架时间列for col_name in row.index:if isinstance(col_name, str) and ("上架时间" in col_name or "上架日期" in col_name):try:# 尝试将上架时间转换为日期对象if pd.notna(row[col_name]):listing_date = pd.to_datetime(row[col_name])# 如果上架时间在半年内,则计为新品if listing_date > half_year_ago:category_stats[category]['new_product_count'] += 1breakexcept:# 如果转换失败,则忽略该行pass# 查找月销量和月销售额列for sales_col in df.columns:if isinstance(sales_col, str):if sales_col == "月销量" or (isinstance(sales_col, str) and sales_col.strip() == "月销量"):# 累加月销量(确保为整数)category_stats[category]['sales_volume'] += int(category_rows[sales_col].sum())elif sales_col.startswith("月销售额"):# 累加月销售额category_stats[category]['sales_amount'] += category_rows[sales_col].sum()elif sales_col.startswith("价格"):# 累加价格category_stats[category]['price_sum'] += category_rows[sales_col].sum()elif sales_col.startswith("评分数"):# 累加评分数category_stats[category]['review_sum'] += category_rows[sales_col].sum()# 计算总计total_sales_volume = 0total_sales_amount = 0total_asin_count = 0total_price_sum = 0total_review_sum = 0# 为每个分类随机选择一个图片for i, category in enumerate(categories):if category_images[category]:# 从该分类的图片中随机选择一个random_image_idx = np.random.randint(0, len(category_images[category]))random_image = category_images[category][random_image_idx]# 填充结果DataFramefor i, category in enumerate(categories):# 获取该分类的统计数据stats = category_stats[category]# 月销量(确保为整数)sales_volume = int(stats['sales_volume'])result_df.loc[2, chr(66 + i)] = sales_volumetotal_sales_volume += sales_volume# 月销售额sales_amount = stats['sales_amount']result_df.loc[3, chr(66 + i)] = sales_amounttotal_sales_amount += sales_amount# ASIN数asin_count = stats['asin_count']result_df.loc[5, chr(66 + i)] = asin_counttotal_asin_count += asin_count# 平均月销售额 = 月销售额 / ASIN数avg_sales_amount = sales_amount / asin_count if asin_count > 0 else 0result_df.loc[4, chr(66 + i)] = avg_sales_amount# 平均价格 = 价格总和 / ASIN数price_sum = stats['price_sum']avg_price = price_sum / asin_count if asin_count > 0 else 0result_df.loc[6, chr(66 + i)] = avg_pricetotal_price_sum += price_sum# 平均review = 评分总和 / ASIN数review_sum = stats['review_sum']avg_review = review_sum / asin_count if asin_count > 0 else 0result_df.loc[7, chr(66 + i)] = avg_reviewtotal_review_sum += review_sum# 添加总计列result_df.loc[2, chr(66 + len(categories))] = int(total_sales_volume) # 月销量总计(确保为整数)result_df.loc[3, chr(66 + len(categories))] = total_sales_amount # 月销售额总计result_df.loc[5, chr(66 + len(categories))] = total_asin_count # ASIN数总计# 总体平均月销售额 = 总月销售额 / 总ASIN数total_avg_sales_amount = total_sales_amount / total_asin_count if total_asin_count > 0 else 0result_df.loc[4, chr(66 + len(categories))] = total_avg_sales_amount# 总体平均价格 = 总价格总和 / 总ASIN数total_avg_price = total_price_sum / total_asin_count if total_asin_count > 0 else 0result_df.loc[6, chr(66 + len(categories))] = total_avg_price# 总体平均review = 总review总和 / 总ASIN数total_avg_review = total_review_sum / total_asin_count if total_asin_count > 0 else 0result_df.loc[7, chr(66 + len(categories))] = total_avg_review# 计算月销量占比和月销售额占比for i, category in enumerate(categories):# 月销量占比sales_volume = int(result_df.loc[2, chr(66 + i)]) # 确保为整数sales_volume_percentage = (sales_volume / total_sales_volume * 100) if total_sales_volume > 0 else 0result_df.loc[8, chr(66 + i)] = sales_volume_percentage# 月销售额占比sales_amount = float(result_df.loc[3, chr(66 + i)])sales_amount_percentage = (sales_amount / total_sales_amount * 100) if total_sales_amount > 0 else 0result_df.loc[9, chr(66 + i)] = sales_amount_percentage# 计算半年新品总数total_new_product_count = 0for category in categories:new_product_count = category_stats[category]['new_product_count']result_df.loc[11, chr(66 + categories.index(category))] = new_product_counttotal_new_product_count += new_product_count# 添加半年新品总数到总计列result_df.loc[11, chr(66 + len(categories))] = total_new_product_count# 计算ASIN占比for i, category in enumerate(categories):asin_count = float(result_df.loc[5, chr(66 + i)])asin_percentage = (asin_count / total_asin_count * 100) if total_asin_count > 0 else 0result_df.loc[10, chr(66 + i)] = asin_percentage# 计算半年新品占比for i, category in enumerate(categories):new_product_count = float(result_df.loc[11, chr(66 + i)])new_product_percentage = (new_product_count / total_new_product_count * 100) if total_new_product_count > 0 else 0result_df.loc[12, chr(66 + i)] = new_product_percentage# 总计列的占比都是100%result_df.loc[8, chr(66 + len(categories))] = 100 # 月销量占比result_df.loc[9, chr(66 + len(categories))] = 100 # 月销售额占比result_df.loc[10, chr(66 + len(categories))] = 100 # ASIN占比result_df.loc[12, chr(66 + len(categories))] = 100 # 半年新品占比# 将数据框转换为字符串类型以避免Arrow兼容性问题# 但先保存一个数值版本用于Excel导出result_df_numeric = result_df.copy()# 显示结果(转换为字符串以避免Arrow兼容性问题)st.subheader("处理后的数据")# 格式化数值显示display_df = result_df.copy()for i in range(2, 13): # 处理第3-13行(索引2-12)的数值格式for j in range(1, len(categories) + 2): # B列到最后一列col = chr(65 + j)if i in [4, 6, 7]: # 平均月销售额、平均价格、平均review保留2位小数try:display_df.loc[i, col] = f"{float(display_df.loc[i, col]):.2f}"except:passelif i in [8, 9, 10, 12]: # 月销量占比、月销售额占比、ASIN占比、半年新品占比保留2位小数并添加%符号try:display_df.loc[i, col] = f"{float(display_df.loc[i, col]):.2f}%"except:passelif i in [2, 3, 5, 11]: # 销量、销售额、ASIN数、半年新品数量使用千分位分隔符try:display_df.loc[i, col] = f"{int(float(display_df.loc[i, col])):,}"except:passst.dataframe(display_df)# 提供下载功能# 创建一个新的BytesIO对象output = io.BytesIO()# 预处理所有数据export_df = result_df_numeric.copy()# 1. 预处理百分比数据for i in [8, 9, 10, 12]: # 月销量占比、月销售额占比、ASIN占比、半年新品占比for j in range(1, len(categories) + 2):col = chr(65 + j)try:cell_value = export_df.loc[i, col]if pd.notna(cell_value):# 将百分比值除以100转换为小数export_df.loc[i, col] = float(cell_value) / 100except:pass# 2. 处理小数值(平均月销售额、平均价格、平均review)for i in [4, 6, 7]: # 平均月销售额、平均价格、平均reviewfor j in range(1, len(categories) + 2):col = chr(65 + j)try:cell_value = export_df.loc[i, col]if pd.notna(cell_value):# 将小数值四舍五入为两位小数export_df.loc[i, col] = round(float(cell_value), 2)except:pass# 3. 处理销售额(保留两位小数)for j in range(1, len(categories) + 2):col = chr(65 + j)try:cell_value = export_df.loc[3, col] # 月销售额在第4行(索引3)if pd.notna(cell_value):export_df.loc[3, col] = round(float(cell_value), 2)except:pass# 写入Excelwith pd.ExcelWriter(output, engine='openpyxl') as writer:# 直接写入数据,不包含表头export_df.to_excel(writer, sheet_name="汇总结果", index=False, header=False)# 获取工作表workbook = writer.bookworksheet = writer.sheets["汇总结果"]# 设置图片行的高度为150worksheet.row_dimensions[2].height = 150# 设置A列宽度为15worksheet.column_dimensions['A'].width = 15# 设置所有分类列的宽度为25for i in range(len(categories) + 1):col_letter = chr(66 + i) # B, C, D...worksheet.column_dimensions[col_letter].width = 25 # Excel列宽单位约为7像素# 将已经在网页上显示的随机图片添加到工作表中for i, category in enumerate(categories):if category in export_images:# 使用之前选择的随机图片,但重新创建新的Image对象img_data = export_images[category]img_cell = chr(66 + i) + "2" # B2, C2, D2...等单元格# 重新创建XLImage对象而不是直接使用原来的new_img = XLImage(io.BytesIO(img_data))worksheet.add_image(new_img, img_cell)# 导入所需的样式模块from openpyxl.styles import numbers, Font, Border, Side, Alignment# 定义边框样式 - 实线边框thin_border = Border(left=Side(style='thin'),right=Side(style='thin'),top=Side(style='thin'),bottom=Side(style='thin'))# 定义粗体字体bold_font = Font(bold=True)# 对A列标题加粗for i in range(13): # 假设有13行数据cell = worksheet.cell(row=i+1, column=1) # A列cell.font = bold_font# 为所有单元格添加边框# 获取工作表的最大行和列max_row = 13 # 根据您的数据结构,可能需要调整max_col = len(categories) + 2 # A列 + 所有分类列 + 总计列for row in range(1, max_row + 1):for col in range(1, max_col + 1):cell = worksheet.cell(row=row, column=col)cell.border = thin_border# 对所有数值应用格式# 1. 对百分比列应用格式for i in [8, 9, 10, 12]: # 月销量占比、月销售额占比、ASIN占比、半年新品占比for j in range(1, len(categories) + 2):# 计算单元格位置(不考虑标题行)cell = worksheet.cell(row=i+1, column=j+1) # +1是因为没有标题行,只考虑索引从0开始# 设置为百分比格式cell.number_format = '0.00%'# 2. 对小数值应用格式(平均月销售额、平均价格、平均review)for i in [4, 6, 7]: # 平均月销售额、平均价格、平均reviewfor j in range(1, len(categories) + 2):cell = worksheet.cell(row=i+1, column=j+1)cell.number_format = '0.00'# 3. 对整数值应用千分位格式(月销量、月销售额、ASIN数、半年新品数量)for i in [2, 3, 5, 11]: # 销量、销售额、ASIN数、半年新品数量for j in range(1, len(categories) + 2):cell = worksheet.cell(row=i+1, column=j+1)# 对于销售额(i=3),设置为带两位小数的千分位格式if i == 3:cell.number_format = '#,##0.00'else:cell.number_format = '#,##0'# 确保output已经被正确写入并准备好读取output.seek(0)# 使用download_button提供下载功能st.download_button(label="下载处理后的Excel文件",data=output,file_name="处理后的数据.xlsx",mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")if uploaded_file is not None:process_excel(uploaded_file)else:st.info("请上传一个Excel文件")
app.py+460-483