美文网首页
ruby excel的简单操作

ruby excel的简单操作

作者: kamionayuki | 来源:发表于2015-05-26 20:24 被阅读729次
    #encoding:utf-8
    require 'win32ole'
    
    PATH = "C:\\Users\\Administrator\\Desktop\\"
    file_name = "123.xls"
    file_path = PATH+file_name
    default_datalist = Array.new(4){|x| Array.new(4){|y| "dfadsf"}}
    
    #写入数据,datalist必须是二维数组
    def writeData(worksheet,datalist)
        datalist.each_with_index do |data, i|
            for j in 0..data.size-1
                j == 0 ? temp = worksheet.Range("a#{i+1}") : temp = temp.next  #next方法是定位到右边的第一个单元格
                temp.value = data[j]
            end
        end
    end
    
    #读取数据
    def readData(worksheet,*args)
        if args.empty?
            cells = worksheet.UsedRange.Rows.value #UsedRange.Rows是取所有的单元格
        else
            cells = worksheet.Range(args[0], args[1]).value
        end
        # cells.each {|cell| cell.each_with_index {|c,i| cell[i] = 0 if c == nil}} #将nil值用0代替
        cells.each {|cell| p cell}
        # p cells
    end
    
    begin
        excel = WIN32OLE::new('Excel.Application')
        excel.WorkBooks.Open(file_path)
        worksheet = excel.ActiveWorkbook.WorkSheets(1)
        #写入数据
        datalist = default_datalist
        writeData(worksheet, datalist)
        #读取数据
        readData(worksheet)
        # p worksheet.Range("a1").next.value
        excel.Quit()
    rescue Exception => e
        puts $!
        puts $@
        excel.Quit()
    end
    

    相关文章

      网友评论

          本文标题:ruby excel的简单操作

          本文链接:https://www.haomeiwen.com/subject/jxyrqttx.html