【问题标题】:Ruby - append existing xlsx into workbookRuby - 将现有的 xlsx 附加到工作簿中
【发布时间】:2018-01-20 04:30:14
【问题描述】:

我在 Ruby 1.9.3(在 Windows 上)中使用 WIN32OLE 创建具有多个工作表的 Excel 工作簿。 我有一个 .xlsx 文件,我希望它成为我新工作簿中的第一个工作表。 怎么做到呢?这是我已经完成的:

my_sheet_file = 'temp.xlsx'
begin
  xl = WIN32OLE.connect('Excel.Application')
rescue
  xl = WIN32OLE.new('Excel.Application')
end
wb = xl.Workbooks.Add()
ws = wb.Worksheets(1)
ws.Name = "My Sheet"
#need to write temp.xlsx into ws somehow

谢谢。

【问题讨论】:

    标签: ruby excel append win32ole


    【解决方案1】:

    这是我在 Github 上找到的一个 Gem:https://gist.github.com/phollyer/1214475

    #!/usr/bin/env ruby
    require 'spreadsheet'
    
    # Begin Test
    print "Spreadsheet Test\n"
    
    # Create the rows to be inserted
    row_1 = ['A1', 'B1']
    row_2 = ['A2', 'B2']
    
    # Create a new Workbook
    new_book = Spreadsheet::Workbook.new
    
    # Create the worksheet
    new_book.create_worksheet :name => 'Sheet Name'
    
    # Add row_1
    new_book.worksheet(0).insert_row(0, row_1)
    
    # Write the file
    new_book.write('test.xls')
    
    # Wait for the user to inspect the file manually
    print "Sheet Created, press Enter to continue...."
    gets
    
    # Open the previously created Workbook
    open_book = Spreadsheet.open('test.xls')
    
    # Get the row index in order to append a new row 
    # after any exisitng rows with data
    new_row_index = open_book.worksheet(0).last_row_index + 1
    
    # Indicate the row index to the user
    print "Inserting new row at index: #{new_row_index}\n"
    
    # Insert row_2
    open_book.worksheet(0).insert_row(new_row_index, row_2)
    
    # Delete the file so that it can be re-written
    File.delete('test.xls')
    
    # Write out the Workbook again
    open_book.write('test.xls')
    
    # End Test
    print "Test Complete.\n"
    

    【讨论】:

      猜你喜欢
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多