You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python改写代码实现多SampleID数据合并至同一Excel工作表

实现多SampleID数据合并到单个Excel工作表

我懂你现在的困扰:之前尝试用xlsxwriter、pandas处理循环数据时没达到预期效果,现在每个sampleid都生成单独的工作表,想要把所有sampleid的有效数据(第3行及以下的数值部分,不带表头)合并到同一个Excel工作表的连续行里。下面是改写后的代码,完美匹配你的需求:

# 初始化全局变量:主工作表和当前写入行号
main_worksheet = None
current_row = 2  # 对应Excel的第3行,用来开始写入数据
bold = workbook.add_format({'bold': True})

# 仅在第一次执行时创建主工作表并写入表头
if create_an_excel_file_with_one_table:
    main_worksheet = workbook.add_worksheet("All_Samples")
    main_worksheet.set_column('A:AA', 25)
    # 写入统一表头
    main_worksheet.write("A1", "Sampleid:", bold)
    main_worksheet.write("B1", "Consolidated Data", bold)
    main_worksheet.write("A2", "Sample ID", bold)
    main_worksheet.write("B2", "Isotope", bold)
    main_worksheet.write("C2","Activity (Bq/kg)", bold)
    main_worksheet.write("D2",'+/-', bold)
    main_worksheet.write("E2",'1 sd', bold)
    main_worksheet.write("F2","MDA (Bq/kg)", bold)
    # 写入Detector信息(可根据需求调整位置)
    main_worksheet.write(current_row + 10, 3,'Detector:', bold)  # 预留足够空间放数据
    main_worksheet.write(current_row + 10, 4, detector)
    main_worksheet.set_default_row(hide_unused_rows=True)

if sampleid != "000": 
    print(sampleid) 
    print ("Isotope \t", "A (Bq/kg) +/- 1 sd \t MDA (Bq/kg)") 
    # 直接写入主工作表,不再新建子表
    if main_worksheet is not None:
        for i in range(len(activity)):
            if isotopes[i] == "Pb-210": 
                # 每行开头写入当前sampleid,方便区分数据归属
                main_worksheet.write(current_row, 0, sampleid)
                # 写入同位素相关数据
                main_worksheet.write(current_row, 1, isotopes[i]) 
                main_worksheet.write(current_row, 2, str(np.round(activity_pbc[i]/mass,8))) 
                main_worksheet.write(current_row, 3, '+/-') 
                main_worksheet.write(current_row, 4, str(np.round(sigma_activity_pbc[i]/mass,8))) 
                main_worksheet.write(current_row, 5, str(MDA[i]/mass)) 
                # 写完一行后,行号自动+1,确保下一条数据写入下一行
                current_row += 1

workbook.close()

关键改动说明:

  • 全局工作表与行号管理:新增main_worksheet作为唯一的目标工作表,用current_row变量跟踪当前写入位置,每次写完一行数据后自动递增行号,实现数据连续写入。
  • 统一表头仅写一次:把原来每个子表都重复写入的表头逻辑移到主工作表初始化时执行,避免冗余。
  • 新增SampleID标识列:在每行数据最前面加入当前sampleid,合并后能清晰区分每行数据属于哪个样本。
  • 移除子表创建逻辑:删掉了workbook.add_worksheet(sampleid)的代码,所有样本数据都写入同一个主工作表。

如果需要调整表头样式或Detector信息的位置,直接修改对应write方法的参数即可,核心逻辑就是维护全局的写入行号,确保新数据始终追加到上一行的下方。

内容的提问来源于stack exchange,提问作者Roggan1337

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 16:58:12