重新安排excel中重复项的数据

时间:2015-11-30 11:50:32

标签: excel google-sheets

我有一份包含母亲和学生名单的excel表, 每个记录只显示一个学生,但有些妈妈有一个以上的学生 - 这意味着他们有多个记录。 如何将每个妈妈的额外学生转移到妈妈的另一栏?

例如: enter image description here

到此:

enter image description here

1 个答案:

答案 0 :(得分:0)

这是一个简短的红宝石脚本(感谢Yanik Rabe) (开头的复数方法实际上并不是必需的,只是制作更漂亮的错误信息......)

#!/usr/bin/env ruby

# The CSV file to read from
INPUT_FILE = 'sample.csv'

# The CSV file to write to
# This can be the same as INPUT_FILE
# Existing files will be overwritten
OUTPT_FILE = 'sample.out.csv'

# The total number of cells in each row
CELL_COUNT = 10

# The number of cells for each student
# This defines how many columns contain
# student data and will therefore be
# moved to the matching row.
STDT_CELLS = 4

# ----- End of configuration -----

require 'csv'

lines = CSV.read INPUT_FILE

class String
    def pluralize(n, plural = nil)
        noun = \
            if n == 1
                dup
            elsif plural
                plural
            else
                "#{self}s"
            end
        "#{n} #{noun}"
    end
end

class Array
    def real_length
        last_index = 0
        (0..length).each do |i|
            last_index = i if self[i] and not self[i].to_s.empty?
        end
        last_index + 1
    end
end

lines.each_with_index do |line, i|
    next unless line
    if line.length < CELL_COUNT
        missing = CELL_COUNT - line.length
        noun = 'missing cell'.pluralize missing
        STDERR.puts "Warning: #{noun} on line #{i+1} will be filled with an empty string in the output"
        while line.length < CELL_COUNT
            line << ''
        end
    end

    # Check for other entries with the same parent email
    lines.each_with_index do |dline, di|
        next unless dline
        next if i == di
        next if dline.empty?
        if line.first == dline.first
            ((CELL_COUNT - STDT_CELLS)..(CELL_COUNT - 1)).each do |i|
                line[line.real_length] = dline[i]
            end
            lines[di] = nil
        end
    end
end

CSV.open OUTPT_FILE, 'wb' do |csv|
    lines.each do |line|
        csv << line if line
    end
end

puts "Read #{INPUT_FILE} (#{lines.length} lines), wrote #{OUTPT_FILE} (#{lines.compact.length} lines). Have a nice day!"