在rails app中使用Spreadsheet gem下载excel文件

时间:2022-01-06 19:31:37

I am using the Spreadsheet gem in a rails app and want to be able to download an excel file generated by Spreadsheet. I have the following action in my controller:

我在rails应用程序中使用Spreadsheet gem并希望能够下载由Spreadsheet生成的excel文件。我的控制器中有以下操作:

def download_xls
  send_data  spreadsheet_report("Test",  Prospects::INQUIRY_COLUMN_ORDER),
    :filename => "Test.xls",
    :type => "application/vnd.ms-excel"
end

The spreadsheet_report method is defined in the same controller:

spreadsheet_report方法在同一个控制器中定义:

def spreadsheet_report(excel_filename, inquiry_column_order)
  book = Spreadsheet::Workbook.new
  sheet1 = book.create_worksheet :name => Array1[0]
  sheet2 = book.create_worksheet :name => Array2[1]

  rownum = 0
  for column in inquiry_column_order
    sheet1.row(rownum).push column
  end

  book.write "#{excel_filename}.xls"
end

The "Test.xls" file downloads fine, but seems to be losing the necessary formatting, with only one worksheet being created and it having only values on the first row that stretch on and on, such as "@biff_version=1536". I am opening it with LibreOffice Calc so I don't know if that causes some issues but I am able to generate the file just fine and open it with LibreOffice Calc outside of the send_data context. What am I missing?

“Test.xls”文件下载得很好,但似乎正在丢失必要的格式,只创建了一个工作表,并且第一行上的值只有拉伸和打开,例如“@ biff_version = 1536”。我用LibreOffice Calc打开它,所以我不知道是否会导致一些问题,但我能够生成文件,并在send_data上下文之外使用LibreOffice Calc打开它。我错过了什么?

1 个解决方案

#1


1  

Sheet 2 is being created but not shown because there isn't anything in it.

工作表2正在创建但未显示,因为其中没有任何内容。

Just throw in -

刚投入 -

sheet2.row(0).push 'Test Row'

to see if anything gets put into the second sheet.

看看是否有任何东西放入第二张纸。

For the rows, by looking at your code your not incrementing rownum everytime you loop through each column in inquiry_column_order.

对于行,通过查看代码,每次循环查询inquiry_column_order中的每一列时,不会递增rownum。

Just add

只需添加

rownum += 1    

in your for loop after you push data onto the sheet. Hope that works, I just started using spreadsheet today aswell :)

将数据推送到工作表后,在for循环中。希望有效,我今天刚开始使用电子表格以及:)

#1


1  

Sheet 2 is being created but not shown because there isn't anything in it.

工作表2正在创建但未显示,因为其中没有任何内容。

Just throw in -

刚投入 -

sheet2.row(0).push 'Test Row'

to see if anything gets put into the second sheet.

看看是否有任何东西放入第二张纸。

For the rows, by looking at your code your not incrementing rownum everytime you loop through each column in inquiry_column_order.

对于行,通过查看代码,每次循环查询inquiry_column_order中的每一列时,不会递增rownum。

Just add

只需添加

rownum += 1    

in your for loop after you push data onto the sheet. Hope that works, I just started using spreadsheet today aswell :)

将数据推送到工作表后,在for循环中。希望有效,我今天刚开始使用电子表格以及:)