2017-04-07 44 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)您的答案添加一个解释,并指出适用的限制和假设。 –

相关问题