Rails 下載文件

雖然下載文件有 Rails 默認的 send_datasend_file 方法,還有像 axlsx_rails 這樣的第三方庫。但是我仍然比較傾向于使用 Spreedsheet XML 的方式去開發下載文件的功能。

配置 config/initializers/mime_types.rb 文件,使 Rails 能夠支持導出文件的后綴名。

Mime::Type.register "application/csv", :csv
Mime::Type.register "application/xls", :xls

建立 download 方法,并配置好路由。

# app/controllers/orders_controller.rb
def download
  @orders = Order.where(created_at: '2019-01-01'.to_time..'2019-02-01'.to_time)
  respond_to do |format|
    format.csv { send_data @orders.to_csv }
    format.xls { headers["Content-Disposition"] = 'attachment; filename=orders.xls' }
  end
end
# app/models/order.rb
def self.to_csv(options = {})
  CSV.generate(options) do |csv|
    csv.tap do |csv_element|
      all.each do |order|
        csv_element << order.attributes.values_at(*column_names)
      end
    end
  end
end

創建 app/views/orders/download.xls.erb 文件,編寫表格內容。

<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
          xmlns:o="urn:schemas-microsoft-com:office:office"
          xmlns:x="urn:schemas-microsoft-com:office:excel"
          xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
          xmlns:html="http://www.w3.org/TR/REC-html40">
  <Styles>
    <Style ss:ID="s62">
      <NumberFormat ss:Format="&quot;¥&quot;#,##0.00"/>
    </Style>
  </Styles>
  <Worksheet ss:Name="訂單報表">
    <Table>
      <Row>
        <Cell><Data ss:Type="String">訂單名稱</Data></Cell>
        <Cell><Data ss:Type="String">訂單數量</Data></Cell>
        <Cell><Data ss:Type="String">訂單金額</Data></Cell>
        <Cell><Data ss:Type="String">購買用戶</Data></Cell>
        <Cell><Data ss:Type="String">聯系電話</Data></Cell>
        <Cell><Data ss:Type="String">訂單創建時間</Data></Cell>
      </Row>
      <% @orders.each do |order| %>
        <Row>
          <Cell><Data ss:Type="String"><%= order.name %></Data></Cell>
          <Cell><Data ss:Type="Number"><%= order.count %></Data></Cell>
          <Cell ss:StyleID="s62"><Data ss:Type="Number"><%= order.amount %></Data></Cell>
          <Cell><Data ss:Type="String"><%= order.user.nickname %></Data></Cell>
          <Cell><Data ss:Type="String"><%= order.user.mobile %></Data></Cell>
          <Cell><Data ss:Type="String"><%= order.created_at.strftime('%Y-%m-%d %H:%M:%S') %></Data></Cell>
        </Row>
      <% end %>
    </Table>
  </Worksheet>
</Workbook>

現在啟動你的 Rails 應用,訪問 http://localhost:3000/orders/download.xls 就可以導出訂單報表。訪問 http://localhost:3000/orders/download.csv 可以導出 CSV 文件。

參考文檔

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容