是否有任何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. The easiest technique would probably be to rename the file as a .xlsx file, then have Excel open it and save it. 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.
If you have Excel installed you can use the following method to convert a xls file into a xlsx file:
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:
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. First I create a xlsx with axslx, then I convert it via winole into a xls.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.