【问题标题】:Join two spreadsheets on a common column in Excel or OpenOffice在 Excel 或 OpenOffice 的公共列上连接两个电子表格
【发布时间】:2011-05-08 19:07:27
【问题描述】:

我有两个带有公共列的 CSV 文件,我想在公共列上将这些表“连接”在一起。

例如:连接 'A' 和 'B' 等于 'Result'。如果一个表具有另一个表中不存在的键值,则将其保留为空白。

== Table A ==        == Table B ==        == Table result ==
Name  ,Age           Name  ,Sex           Name ,Age ,Sex
Bob   ,37     +      Bob   ,Male     =>   Bob  ,37  ,Male
Steve ,12            Steve ,Male          Steve,12  ,Male
Kate  , 7                                 Kate , 7  , 
                     Sara  ,Female        Sara ,    ,Female 

我知道如何使用 SQL 数据库执行此操作,但我从未使用“Excel”或“OpenOffice.org Calc”完成此操作

建议?

【问题讨论】:

    标签: sql excel openoffice.org openoffice-calc


    【解决方案1】:

    在 Excel 中,vlookup 可以完成您所要求的部分工作。具体来说,您可以使用 vlookup 进行左外连接或右外连接,但不能进行全外连接(如您的表结果)。

    要对上面的示例进行外连接,请将以下内容添加到“表 B”的 C2(或复制“表 B”,然后执行此操作):

    =vlookup(
        a2, # the cell value from the current table to look up in the other table
        table_a!$1:$174832718, # the other table
                               # don't manually type this--select the entire 
                               # other table while the cursor is editing this
                               # cell, then add the "$"s--Excel doesn't
                               # automatically add them
                               # (the syntax here is for different sheets in
                               # the same file, but Excel will fill this in 
                               # correctly for different files as well)
        2, # the column to get from the other table (A=1, B=2, etc.)
        FALSE) # FALSE=only get exact matches TRUE=find approx. matches if no exact match
    

    然后您应该能够扩展它以处理多行和多个导入的列。

    【讨论】:

    • 要做一个完整的外连接,你可以在两个方向上做 VLOOKUP 操作,所以合并表 2 中的表 1 和表 1 中的表 2。然后在宏的帮助下或手动(复制粘贴) 将两个表合并为一个表,并在结果表上使用删除重复项功能。
    • 只是提到第一个变量(在他的情况下为 a2)必须在第一列中才能使 vlookup 工作。
    【解决方案2】:

    在 Excel 中,您为此使用 VLOOKUP
    假设您在 Excel 的 A 列和 B 列中列出了表 A 中的数据。
    表 B 中的数据列在 E 和 F 列中。
    现在,转到 C 列的第一行并输入:

    =VLOOKUP(A:A,E:F,2,FALSE) 
    

    这告诉它尝试将 A 列与 E 列匹配,并抓取第二列中我们找到它的位置附近的任何内容并将其放置在 C 列中。
    现在自动填充 C 列中的其余行以匹配其余数据。

    【讨论】:

      【解决方案3】:

      如果你会使用 Excel,还有一个从 Excel 文件中查询的功能:

      • 定义主表的名称 - 表 A(公式选项卡 -> 定义名称)
      • 为辅助表定义名称 - 表 B
      • 转到“数据”选项卡,选择“来自其他来源”,然后从下拉列表中选择“来自 Microsoft Query”
      • 选择您的 CSV 文件并确认您要手动合并列
      • 在下面的“从 Excel 文件查询”窗口中,将表 A 的名称列拖放到表 B 的名称列中 - 将创建这些列之间的链接
      • 进入文件菜单,点击“返回数据到MS Office Excel”,会弹出导入数据对话框
      • 选择要导入匹配数据的工作表
      • 点击确定 - 您应该会看到两个表中的列匹配的数据

      或者,如果您不介意将 CSV 文件上传到在线服务,您可以使用 http://www.gridoc.com/join-tables 并通过拖放操作加入电子表格(免责声明:我是该工具的作者)。

      希望这会有所帮助。

      【讨论】: