欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用 DataMapper 写入数据到 Excel 文件中

程序员文章站 2022-03-17 17:16:22
...
begin_time = Time.now
puts "Begin: #{begin_time}"
require 'rubygems'
require 'datamapper'
require "spreadsheet/excel"
require "iconv"
include Spreadsheet

ic = Iconv.new("GB2312//IGNORE", "UTF-8//IGNORE")
workbook = Excel.new("D:/xampp/htdocs/rubyshell/sources/demodatas/abc.xls")
DataMapper.setup(:default, 'mysql://localhost/demo_nobel_test')
#固定资产
class FixedAsset
  include DataMapper::Resource
  storage_names[:default] = 'www_fixed_assets'
  
  property :id,   Serial
  property :type, Integer
  property :kindergarten_id, Integer
  property :dept_id, Integer
  property :sn, String
  property :name, String
  property :specification, String
  property :category_id, Integer
end

#日常易耗品
class ExpendableItem
  include DataMapper::Resource
  storage_names[:default] = 'www_expendable_items'
  
  property :id, Serial
  property :category_id, Integer
  property :sn, String
  property :name, String
  property :pinyin, String
  property :specification, String
  property :unit_id, Integer
  property :quantity, Integer
  property :price, Float
  property :amount, Float
  property :early_warning_value, Integer
  property :created, Integer
  property :updated, Integer
end

#日常易耗品分类
class GoodCategory
  include DataMapper::Resource
  storage_names[:default] = 'www_goods_categories'
  
  property :id, Serial
  property :name, String
  property :parent_id, Integer
end


# Log for processed
class Log
  def initialize

  end

  def write
    now = Time.now
    puts now
  end
end

# 生成日常易耗品报表 begin
times = 0
good_categories = GoodCategory.all(:parent_id.gt => 0)
good_categories.each do |good_category|
  worksheet = workbook.add_worksheet(ic.iconv(good_category.name))
  i = 0
  worksheet.write(0, 0, ic.iconv('序号'))
  worksheet.write(0, 2, ic.iconv('编号'))
  worksheet.write(0, 3, ic.iconv('品名'))
  worksheet.write(0, 4, ic.iconv('规格'))
  i += 1  
  expendable_items = ExpendableItem.all(:conditions => {:category_id => good_category.id})

  expendable_items.each do |item|
    worksheet.write(i, 0, i)
    worksheet.write(i, 2, item.sn)
    worksheet.write(i, 3, ic.iconv(item.name))
    worksheet.write(i, 4, ic.iconv(item.specification))
    i += 1
    times += 1
    puts "Processing #{times} record, Please watting......"
  end
  
end
workbook.close
end_time = Time.now
puts "End: #{end_time}"
puts ic.iconv("向 Excel 文件中写入 #{times} 条数据,耗时: #{end_time.to_i - begin_time.to_i} 秒。")
# 生成日常易耗品报表 end