1

我需要的

是否可以在将 Nokogiri 输出发送到 Excel 等电子表格之前对其进行格式化?

示例:http ://www.asus.com/Notebooks_Ultrabooks/ASUS_TAICHI_21/#specifications 上 的表格格式很好,可以使用电子表格 gem 将类似的格式应用于 Nokogiri 输出吗?

我的代码

require 'nokogiri'
require 'open-uri'
require 'spreadsheet'

doc = Nokogiri::HTML(open("http://www.asus.com/Notebooks_Ultrabooks/ASUS_TAICHI_21/#specifications"))

#Grab our product specifications
data = doc.css('div#specifications div#spec-area ul.product-spec li')

#Modify our data
lines = data.map(&:text).join("\n")

#Create the Spreadsheet
Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet::Workbook.new

sheet1 = book.create_worksheet
sheet1.name = 'My First Worksheet'

#Output our data  to the Spreadsheet
sheet1[0,0] = lines
book.write 'C:/Users/Barry/Desktop/output.xls'
4

1 回答 1

0

您的代码创建了一个单行电子表格,其中有一列。该列是所有行的串联。

要将每一行放入自己的列中,然后:

lines = data.map(&:text)
...
lines.each.with_index do |line, i|                                                        |
  sheet1[0, i] = line                                                                     |
end                                                                                       |
book.write '/tmp/output.xls'                                                              |

要将每一行放入自己的行中,然后:

lines = data.map(&:text)
...
lines.each.with_index do |line, i|                                                        |
  sheet1[i, 0] = line                                                                     |
end                                                                                       |
book.write '/tmp/output.xls'                                                              |
于 2013-02-03T13:15:20.670 回答