解决方法
使用
Sequel和
to_csv
很容易:
require 'sequel' DB = Sequel.sqlite # since Sequel 3.48.0 to_csv is deprecated,# we must load the to_csv feature via a extension DB.extension(:sequel_3_dataset_methods) #define to_csv DB.create_table(:test){ Fixnum :one Fixnum :two Fixnum :three } #Prepare some test data 5.times{|i| DB[:test].insert(i,i*2,i*3) } File.open('test.csv','w'){|f| f << DB[:test].to_csv }
结果是:
one,two,three 0,0 1,2,3 2,4,6 3,6,9 4,8,12
在我的测试中我遇到了线端问题,所以我需要一个额外的gsub:
File.open('test.csv','w'){|f| f << DB[:test].to_csv.gsub("\r\n","\n") }
如果您想要不带标题行的导出,请使用to_csv(false)
备注:
> .to_csv自续集3.48.0(2013-06-01)后被弃用.
你可以使用旧版本的宝石’续集’,’< 3.48.0'或加载扩展名sequel_3_dataset_methods).
要获得对其他分隔符和其他CSV功能的支持,您可以使用续集和CSV的组合:
require 'sequel' require 'csv' #Build test data DB = Sequel.sqlite DB.create_table(:test){ Fixnum :one Fixnum :two Fixnum :three String :four } #Prepare some test data 5.times{|i| DB[:test].insert(i,i*3,'<a href="www.test.com">test,no %i</a>' % i) } #Build csv-file File.open('test.csv','w'){|f| DB[:test].each{|data| f << data.values.to_csv(:col_sep=>';') } }
结果:
0;0;0;"<a href=""www.test.com"">test,no 0</a>" 1;2;3;"<a href=""www.test.com"">test,no 1</a>" 2;4;6;"<a href=""www.test.com"">test,no 2</a>" 3;6;9;"<a href=""www.test.com"">test,no 3</a>" 4;8;12;"<a href=""www.test.com"">test,no 4</a>"
作为替代方案,您可以修补Sequel :: Dataset(修改后的代码来自marcalc at Github):
class Sequel::Dataset require 'csv' # #Options: #* include_column_titles: true/false. default true #* Other options are forwarded to CSV.generate def to_csv(options={}) include_column_titles = options.delete(:include_column_titles){true} #default: true n = naked cols = n.columns csv_string = CSV.generate(options) do |csv| csv << cols if include_column_titles n.each{|r| csv << cols.collect{|c| r[c] } } end csv_string end end