6

我有以下后台作业,它写入 csv 文件并通过电子邮件发送出去。我正在使用 Tempfile 类,因此在将文件通过电子邮件发送给用户后会删除该文件。目前,当我查看 csv 文件时,我生成的结果如下所示:

["Client Application"    "Final Price"   "Tax"   "Credit"    "Base Price"    "Billed At"     "Order Guid"    "Method of Payment Guid"    "Method of Payment Type"]
["web"   nil     nil     nil     nil     nil     nil     "k32k313k1j3"   "credit card"]

请忽略数据,但问题是,它是直接以 ruby​​ 格式写入文件的,而不是删除“”和 [] 字符。

请看下面的代码:

class ReportJob
@queue = :report_job

 def self.perform(client_app_id, current_user_id)
  user = User.find(current_user_id)
  client_application = Application.find(client_app_id)
  transactions = client_application.transactions
  file = Tempfile.open(["#{Rails.root}/tmp/", ".csv"]) do |csv|
    begin
     csv << ["Application", "Price", "Tax", "Credit", "Base Price", "Billed At", "Order ID", "Payment ID", "Payment Type"]
     transactions.each do |transaction|
      csv << "\n"
      csv << [application.name, transaction.price, transaction.tax, transaction.credit, transaction.base_price, transaction.billed_at, transaction.order_id, transaction.payment_id, transaction.payment_type]
    end
   ensure
    ReportMailer.send_rev_report(user.email, csv).deliver
    csv.close(unlink_now=false)
    end
  end
end

end

这会是使用 tempfile 类而不是 csv 类的问题吗?或者我可以做些什么来改变它被写入文件的方式?

在邮件程序中添加用于读取 csv 文件的代码。我目前收到一个 TypeError,上面写着“无法将 CSV 转换为字符串”。

class ReportMailer < ActionMailer::Base
 default :from => "test@gmail.com"

  def send_rev_report(email, file)
     attachments['report.csv'] = File.read("#{::Rails.root.join('tmp', file)}")
      mail(:to => email, :subject => "Attached is your report")
    end
  end
end
4

4 回答 4

15

问题是您实际上并没有将 csv 数据写入文件。您正在将数组发送到文件句柄。我相信你需要类似的东西:

Tempfile.open(....) do |fh|
    csv = CSV.new(fh, ...)
    <rest of your code>
end

正确设置 CSV 输出过滤。

于 2013-01-28T14:36:36.783 回答
3

我更喜欢做

tempfile = Tempfile.new(....)
csv = CSV.new(tempfile, ...) do |row|
  <rest of your code>
end
于 2016-05-20T22:05:52.290 回答
2

这就是我的做法。

patient_payments = PatientPayment.all

Tempfile.new(['patient_payments', '.csv']).tap do |file|
  CSV.open(file, 'wb') do |csv|
    csv << patient_payments.first.class.attribute_names

    patient_payments.each do |patient_payment|
      csv << patient_payment.attributes.values
    end
  end
end
于 2020-05-05T00:22:49.247 回答
1

试试这个:

Tempfile.open(["#{Rails.root}/tmp/", ".csv"]) do |outfile|
  CSV::Writer.generate(outfile) do |csv|
    csv << ["Application", "Price", "Tax", "Credit", "Base Price", "Billed At", "Order ID", "Payment ID", "Payment Type"]
    #...
  end
end
于 2013-01-28T15:14:58.960 回答