ruby max_value_importer.rb

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby max_value_importer.rb相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# max_value_importer.rb --file "./abc.xlsx" --sheet "sheet1" --date_range "A2:A100" --value_range "B2:B100" --date_cell "d2" --value_cell "e2"

require 'csv'
require 'optparse'
require 'win32ole'

class WIN32OLE
  def to_a
    [].tap do |array|
      each { |o| array.push o }
    end
  end
end

class MaxValueImporter
  def initialize
    params = optparse
    @file = absolute_path params['file']
    @sheet = params['sheet']
    @date_range = params['date_range']
    @value_range = params['value_range']
    @date_cell = params['date_cell']
    @value_cell = params['value_cell']
    write_excel
  end

  def open_book(file)
    excel = WIN32OLE.new 'Excel.Application'
    excel.visible = false

    begin
      book = excel.Workbooks.Open file
      yield book
    ensure
      book.Close
      excel.Quit
    end
  end

  def write_excel
    open_book @file do |book|
      sheet = book.Worksheets @sheet
      dates = sheet.Range(@date_range)
                   .to_a
                   .each
                   .map(&:value)
                   .compact
      values = sheet.Range(@value_range)
                    .to_a
                    .each
                    .map(&:value)
                    .compact
      max_index = values
                  .each_with_index
                  .map { |value, i| value == values.max ? i : nil }
                  .compact
                  .first
      sheet.Range(@date_cell).Value = dates[max_index]
      sheet.Range(@value_cell).Value = values.max
      book.Save
    end
  end

  def optparse
    params = ARGV.getopts('', 'file:', 'sheet:', 'date_range:', 'value_range:',
                          'date_cell:', 'value_cell:')
    params
  end

  def absolute_path(file)
    fso = WIN32OLE.new 'Scripting.FileSystemObject'
    fso.GetAbsolutePathName file
  end
end

MaxValueImporter.new if $PROGRAM_NAME == __FILE__

以上是关于ruby max_value_importer.rb的主要内容,如果未能解决你的问题,请参考以下文章

Ruby 25 岁了!Ruby 之父说 Ruby 3 有望 3 倍提速

如何学习ruby?Ruby学习技巧分享

ruby Ruby脚本,看看是否用openssl编译了ruby

什么是ruby?

ruby和ruby ee

ruby入门知识:了解ruby历史及特性