2017-04-07 28 views
0

我正在使用電子表格gem來生成.xls文件。將它寫入文件後,我正在嘗試發送到客戶端瀏覽器進行下載。使用rails&angular爲瀏覽器提供excel表單(.xls)

下面是軌道

workbook = Spreadsheet::Workbook.new 
# Constructed the data 
file = "/path/to/file/sheet.xls" 
workbook.write file 
send_file file 

打開時包含預期理想格式數據此文件中的代碼。

下面是JS代碼:

CustomRestService.custom_post("report",{report_data: angular.toJson($scope.report_data)},"download_xls",{}).then (data)-> 
    if data 
     hiddenElement = document.createElement('a') 
     angular.element(document.body).append(hiddenElement) 
     hiddenElement.href = 'data:attachment/xls,' + encodeURI(data) 
     hiddenElement.target = '_blank' 
     hiddenElement.download = "report.xls" 
     hiddenElement.click() 
     hiddenElement.remove() 

但在瀏覽器中的文件中獲取下載包含垃圾數據。我試着像下面多個解決方案:

  1. 使用SEND_DATA,而不是由send_file
  2. 生成XLS數據,並寫信給StringIO對象直接下載
  3. 構建Blob對象的JS,類型爲「應用程序/越南盾。 ms-excel「並嘗試下載它。

所有嘗試失敗,因爲我失去了一些東西。所有建議都歡迎。

回答

0
filename = "/path/to/file/sheet.xls" 
tempfile = Tempfile.new(filename) 
workbook = Spreadsheet::Workbook.new 
... 
workbook.write(tempfile.path) 
send_file tempfile.path, :filename => filename 
+0

儘管此代碼可以回答這個問題,提供額外的[背景](https://meta.stackexchange.com/q/114762)關於_how_和/或_why_它解決了問題,將改善答案的長長期價值。請記住,你正在爲將來的讀者回答這個問題,而不僅僅是現在問的人!請[編輯](http://stackoverflow.com/posts/43297411/edit)您的答案添加一個解釋,並指出適用的限制和假設。 –

相關問題