-->

如何查询MS Access数据库表,并使用Ruby的信息导出到Excel和WIN32OLE?(How

2019-10-17 22:27发布

我是新来的Ruby和我试图查询现有的MS Access数据库的报告信息。 我想存储在一个Excel文件信息。 我会怎么做呢?

Answer 1:

尝试下列操作之一:

OLE:

require 'win32ole'

class AccessDbExample
  @ado_db = nil

  # Setup the DB connections
  def initialize filename
    @ado_db             = WIN32OLE.new('ADODB.Connection')
    @ado_db['Provider'] = "Microsoft.Jet.OLEDB.4.0"
    @ado_db.Open(filename)
  rescue Exception => e
    puts "ADO failed to connect"
    puts e
  end

  def table_to_csv table
    sql = "SELECT * FROM #{table};"

    results = WIN32OLE.new('ADODB.Recordset')
    results.Open(sql, @ado_db)

    File.open("#{table}.csv", 'w') do |file|
      fields = []
      results.Fields.each{|f| fields << f.Name}
      file.puts fields.join(',')

      results.GetRows.transpose.each do |row|
        file.puts row.join(',')
      end
    end unless results.EOF

    self
  end

  def cleanup
    @ado_db.Close unless @ado_db.nil?
  end
end

AccessDbExample.new('test.mdb').table_to_csv('colors').cleanup

ODBC:

  require 'odbc'

    include ODBC

    class AccessDbExample
      @obdc_db = nil

      # Setup the DB connections
      def initialize filename
        drv                 = Driver.new
        drv.name            = 'AccessOdbcDriver'
        drv.attrs['driver'] = 'Microsoft Access Driver (*.mdb)'
        drv.attrs['dbq']    = filename
        @odbc_db            = Database.new.drvconnect(drv) 
      rescue 
          puts "ODBC failed to connect"
      end

      def table_to_csv table
        sql = "SELECT * FROM #{table};"

        result = @odbc_db.run(sql)
        return nil if result == -1

        File.open("#{table}.csv", 'w') do |file|
          header_row = result.columns(true).map{|c| c.name}.join(',')
          file.puts header_row

          result.fetch_all.each do |row|
            file.puts row.join(',')
          end
        end

        self
      end

      def cleanup
        @odbc_db.disconnect unless @odbc_db.nil?
      end
    end

    AccessDbExample.new('test.mdb').table_to_csv('colors').cleanup


Answer 2:

你为什么要这么做? 你可以简单地从Excel中直接查询您的分贝。 看看这个教程 。



Answer 3:

正如约翰说,你可以查询从Excel数据库。

但是,如果你更喜欢使用Ruby的工作...

你可以找到关于查询访问/喷气数据库使用Ruby的信息在这里 。

与红宝石自动化Excel信息的地段,可以发现在这里 。

大卫



文章来源: How do I query a MS Access database table, and export the information to Excel using Ruby and win32ole?