[英]Convert from Excel xls to xlsx in ruby
是否有任何gem /插件/代码片段将使用ruby从Excel xls转换为xlsx
Assuming you have excel installed, you should be able to use win32ole (http://ruby-doc.org/stdlib/libdoc/win32ole/rdoc/index.html) to script Excel. 假设你已经安装了excel,你应该可以使用win32ole(http://ruby-doc.org/stdlib/libdoc/win32ole/rdoc/index.html)来编写Excel脚本。 The easiest technique would probably be to rename the file as a .xlsx file, then have Excel open it and save it.
最简单的技术可能是将文件重命名为.xlsx文件,然后让Excel打开并保存。 That's probably easier than trying to script your way through a "save as" operation.
这可能比通过“另存为”操作尝试编写脚本更容易。
It's not a Ruby solution, but I've also scripted the Excel interface using AutoIt. 它不是Ruby解决方案,但我也使用AutoIt编写Excel界面脚本。
If you have Excel installed you can use the following method to convert a xls file into a xlsx file: 如果安装了Excel,则可以使用以下方法将xls文件转换为xlsx文件:
require 'win32ole'
def xls2xlsx(path, target = nil)
raise ArgumentError unless path =~ /.xls\Z/
raise ArgumentError unless File.exist?(path)
target = path + 'x' unless target # Save the workbook. / must be \
puts "convert %s to %s" % [path, target]
# Create an instance of the Excel application object
xl = WIN32OLE.new('Excel.Application')
# Make Excel visible 1=visible 0=not visible
xl.Visible = 1
#~ xl.Interactive = false #visible, but no input allowed
#~ xl.ScreenUpdating = false #make it faster
xl.DisplayAlerts = false #No alerts like "don't overwrite
# Add a new Workbook object
wb = xl.Workbooks.Open(File.expand_path(path))
wb.SaveAs(File.expand_path(target).gsub!(/\//, '\\'), 51 ) #excel 2007
# Close the workbook
wb.Close
# Quit Excel
xl.Quit
end
If you need th other way (xlsx to xls) you can use: 如果您需要其他方式(xlsx到xls),您可以使用:
def xlsx2xls(path, target = nil)
raise ArgumentError unless path =~ /.xlsx\Z/
raise ArgumentError unless File.exist?(path)
target = path.chop unless target # Save the workbook. / must be \
puts "convert %s to %s" % [path, target]
# Create an instance of the Excel application object
xl = WIN32OLE.new('Excel.Application')
# Make Excel visible 1=visible 0=not visible
xl.Visible = 1
#~ xl.Interactive = false #visible, but no input allowed
#~ xl.ScreenUpdating = false #make it faster
xl.DisplayAlerts = false #No alerts like "don't overwrite
# Add a new Workbook object
wb = xl.Workbooks.Open(File.expand_path(path))
wb.SaveAs(File.expand_path(target).gsub!(/\//, '\\'), -4143 ) #excel97_2003_format
# Close the workbook
wb.Close
# Quit Excel
xl.Quit
end
I use the 2nd method in combination with axlsx to get a xls-file. 我将第二种方法与axlsx结合使用来获取xls文件。 First I create a xlsx with axslx, then I convert it via winole into a xls.
首先,我使用axslx创建一个xlsx,然后通过winole将其转换为xls。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.