ruby-on-rails – 在ruby中有效地将Excel转换为CSV

我使用 spreadsheet gem来做到这一点.它有效,但有时可能非常慢.我甚至尝试过 Roo gem,但这并没有改善性能.有没有更好的方法来完成这项工作?奇怪的是,同一个excel中的一些工作表工作得更快,一些工作表工作得非常慢,甚至需要长达1小时.

我们可以使用开放式办公室在单个Excel中打开每个工作表(选项卡)并将它们更快地转换为csv吗?如果是的话,我将如何在ruby中做到这一点?

或者是否有更好的解决方案?

只是添加一个我尝试使用Roo gem的小例子

xls = Roo::Excel.new(source_excel_file)
xls.each_with_pagename do |name,sheet|
  # p sheet.to_csv(File.join(dest_csv_dir,name + ".csv"))
  #sheet.parse(:clean => true)#.to_csv(File.join(dest_csv_dir,name + ".csv"))
  puts name
  puts sheet.parse(:clean => true)
end

解决方法

懦弱的前言:我对ruby很陌生,对滚道几乎一无所知,但我之前曾与Excel纠缠在一起.我在本地机器上创建了一个虚拟工作簿,有5张,每张包含10列和1000行随机生成的数字.我将每张表格转换为自己的CSV格式:
require 'win32ole'
require 'csv'

# configure a workbook,turn off excel alarms
xl = WIN32OLE.new('excel.application')
book = xl.workbooks.open('C:\stack\my_workbook.xlsx')
xl.displayalerts = false

# loop through all worksheets in the excel file
book.worksheets.each do |sheet|
  last_row = sheet.cells.find(what: '*',searchorder: 1,searchdirection: 2).row
  last_col = sheet.cells.find(what: '*',searchorder: 2,searchdirection: 2).column
  export = File.new('C:\\stack\\' + sheet.name + '.csv','w+')
  csv_row = []

  # loop through each column in each row and write to CSV
  (1..last_row).each do |xlrow|
    (1..last_col).each do |xlcol|
      csv_row << sheet.cells(xlrow,xlcol).value
    end
    export << CSV.generate_line(csv_row)
    csv_row = []
  end
end

# clean up
book.close(savechanges: 'false')
xl.displayalerts = true
xl.quit

这个脚本的眼球基准是大约30秒,每次尝试都在几秒钟之内或之下.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...