rails - 将 xls 文件附加到电子邮件
rails - attach xls file to email
我创建了一个生成 xls 文件的代码,然后我将它传递给 Mailer 以将其作为附件发送。但是,我一次又一次地遇到同样的错误:
TypeError: no implicit conversion of Spreadsheet::Workbook into String
或者
NoMethodError: undefined method `length' for #<Spreadsheet::Workbook:0x007fe937e4fe80>
我的代码是:
def xls_mailer (data)
attachments['HelloWorld.xlsx'] = data
mail(subject: "Hi", to: @gmail.email)
end
***data - 是我传递给此方法的 xls 文件。
谢谢前面的各位,
Action Mailer 希望您向它传递一个 File
-like object as an attachment, but your code's passing it the spreadsheet data directly. Fortunately, Ruby has a class called StringIO
,我们可以使用它来将我们的电子表格转换成类似于 File
的东西:
def xls_mailer (spreadsheet)
spreadsheet_file = StringIO.new
spreadsheet.write(spreadsheet_file)
attachments['HelloWorld.xls'] = spreadsheet_file
mail(subject: "Hi", to: @gmail.email)
end
好的伙计们,我找到了答案。
代码应该是这样的:
spreadsheet_file = StringIO.new
data.write(spreadsheet_file)
attachments['HelloWorld.xls'] = spreadsheet_file.read
下面的代码块很有魅力。我试过这个,在一个工作应用程序中使用。
def send_excel_report(file_name, emails, subject, email_content, file_path, bcc_emails = [])
attachments["#{file_name}.xls"] = File.read(file_path)
mail(to: emails, subject: subject, from: "my_email@gmail.com", bcc: bcc_emails) do |format|
format.html { render :partial => "users/mail_body"}
end
end
仅供参考:我使用电子表格 gem 创建了 excel
我创建了一个生成 xls 文件的代码,然后我将它传递给 Mailer 以将其作为附件发送。但是,我一次又一次地遇到同样的错误:
TypeError: no implicit conversion of Spreadsheet::Workbook into String
或者
NoMethodError: undefined method `length' for #<Spreadsheet::Workbook:0x007fe937e4fe80>
我的代码是:
def xls_mailer (data)
attachments['HelloWorld.xlsx'] = data
mail(subject: "Hi", to: @gmail.email)
end
***data - 是我传递给此方法的 xls 文件。
谢谢前面的各位,
Action Mailer 希望您向它传递一个 File
-like object as an attachment, but your code's passing it the spreadsheet data directly. Fortunately, Ruby has a class called StringIO
,我们可以使用它来将我们的电子表格转换成类似于 File
的东西:
def xls_mailer (spreadsheet)
spreadsheet_file = StringIO.new
spreadsheet.write(spreadsheet_file)
attachments['HelloWorld.xls'] = spreadsheet_file
mail(subject: "Hi", to: @gmail.email)
end
好的伙计们,我找到了答案。 代码应该是这样的:
spreadsheet_file = StringIO.new
data.write(spreadsheet_file)
attachments['HelloWorld.xls'] = spreadsheet_file.read
下面的代码块很有魅力。我试过这个,在一个工作应用程序中使用。
def send_excel_report(file_name, emails, subject, email_content, file_path, bcc_emails = [])
attachments["#{file_name}.xls"] = File.read(file_path)
mail(to: emails, subject: subject, from: "my_email@gmail.com", bcc: bcc_emails) do |format|
format.html { render :partial => "users/mail_body"}
end
end
仅供参考:我使用电子表格 gem 创建了 excel