Rails如何把数据导出到excel

Rails如何把数据导出到excel,第1张

首先,只是想把一些数据生成excel文件的话,最简单的办法,应该考虑生成CSV,

因为,Ruby支持比较好,而且,你用excel可以直接打开。当然,前提是你的excel没有特别复杂的表结构,样式渲染等

样例如下:

Ruby代码

outfile = Fileopen('csvout', 'wb')

CSV::Writergenerate(outfile) do |csv|

csv << ['c1', nil, '', '"', "\r\n", 'c2']

end

outfileclose

其次,一般用的话可以考虑spreadsheet。就像一楼的老大提供的连接所说,那个例子很好,只是适合你的读取复杂的适合参考。如果,你用不到那么复杂,建议你看下面的说明。

生成excel文件

如果,你想生成一个excel文件,那么首先,就像写文件一个先加载spreadsheet类库,然后,指定编码接着,就可以创建一个Workbook了

Ruby代码

book = Spreadsheet::Workbooknew

在workbook基础上创建Worksheet表单

Ruby代码

sheet1 = bookcreate_worksheet

当然,你也可以用如下方式创建表单:

Ruby代码

sheet2 = bookcreate_worksheet :name => 'My Second Worksheet'

sheet1name = 'My First Worksheet'

那么,这时我们可以采用如下方式加载数据到表单Worksheet#[]=,

Worksheet#update_row, 或者直接给一个指定单元格复制

Ruby代码

sheet1row(0)concat %w{Name Country Acknowlegement}

sheet1[1,0] = 'Japan'

row = sheet1row(1)

rowpush 'Creator of Ruby'

rowunshift 'Yukihiro Matsumoto'

sheet1row(2)replace [ 'Daniel J Berger', 'USA',

'Author of original code for Spreadsheet::Excel' ]

sheet1row(3)push 'Charles Lowe', 'Author of the ruby-ole Library'

sheet1row(3)insert 1, 'Unknown'

sheet1update_row 4, 'Hannes Wyss', 'Switzerland', 'Author'

对于格式的处理,可以如下:

Ruby代码

sheet1row(0)height = 18

format = Spreadsheet::Formatnew :color => :blue,

:weight => :bold,

:size => 18

sheet1row(0)default_format = format

bold = Spreadsheet::Formatnew :weight => :bold

4times do |x| sheet1row(x + 1)set_format(0, bold) end

最后,保存excel文件

Ruby代码

bookwrite '/path/to/output/excel-filexls'

最后,如果是在windows平台下的话,也可以考虑WIN23OLE,处理windows下的转换很强大

Ruby代码

require 'win23ole'

application = WIN32OLEnew('ExcelApplication')

worksheet

=applicationWorkbooksOpen(excelFileName)Worksheets(workSheetName)

worksheetActivate

contLoop = true # Dummy counter for the loop

while contLoop do

colVal = worksheetCells(row, column)Value

if (colVal) then

# 如果这个字段非空,则表示这行有值

# 在这里处理读取

do processing

else

# 这里表明结束。

# End the loop

contLoop = false

end

# go to the next Row

row += 1

end

# we are done

applicationWorkbooksClose

好像lucene现在不能直接根据excel文件创建索引,您需要借助poi把excel文件转成txt等类型的文件。poi解析excel文件的方法请您参考:

>

国内没有办法使用。

目前国内是无法打开google的官方网站的,如果你想使用spreadsheet,你就要自己想办法了。使用spreadsheet,同时需要有google帐号。

以上就是关于Rails如何把数据导出到excel全部的内容,包括:Rails如何把数据导出到excel、如何用poi读取包含多个sheet的excel文档,然后使用lucene创建索引,求高手帮忙、Google spread sheet国内如何用等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9486727.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-28
下一篇2023-04-28

发表评论

登录后才能评论

评论列表(0条)

    保存