`
sg552
  • 浏览: 620051 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
47437293-94b9-3b04-9152-8971c7580049
白手起家学习使用Flex
浏览量:18709
社区版块
存档分类
最新评论

ruby gem SpreadSheet的用法

阅读更多

(官方网站上的链接是失效的。。。所以放这里了,不用每次都 gem server...)


GUIDE.txt

Path: GUIDE.txt
Last Update: Tue Jun 29 10:13:23 +0800 2010

Getting Started with Spreadsheet

This guide is meant to get you started using Spreadsheet. By the end of it, you should be able to read and write Spreadsheets.

Reading is easy!

First, make sure all that code is loaded:

  require 'spreadsheet'

Worksheets come in various Encodings. You need to tell Spreadsheet which Encoding you want to deal with. The Default is UTF-8

  Spreadsheet.client_encoding = 'UTF-8'

Let‘s open a workbook:

  book = Spreadsheet.open '/path/to/an/excel-file.xls'

We can either access all the Worksheets in a Workbook…

  book.worksheets

…or access them by index or name (encoded in your client_encoding)

  sheet1 = book.worksheet 0
  sheet2 = Book.worksheet 'Sheet1'

Now you can either iterate over all rows that contain some data. A call to Worksheet.each without argument will omit empty rows at the beginning of the Worksheet:

  sheet1.each do |row|
    # do something interesting with a row
  end

Or you can tell Worksheet how many rows should be omitted at the beginning. The following starts at the 3rd row, regardless of whether or not it or the preceding rows contain any data:

  sheet2.each 2 do |row|
    # do something interesting with a row
  end

Or you can access rows directly, by their index (0-based):

  row = sheet1.row(3)

To access the values stored in a Row, treat the Row like an Array.

  row[0]

-> this will return a String, a Float, an Integer, a Formula, a Link or a Date or DateTime object - or nil if the cell is empty.

More information about the formatting of a cell can be found in the Format with the equivalent index

  row.format 2

Writing is easy

As before, make sure you have Spreadsheet required and the client_encoding set. Then make a new Workbook:

  book = Spreadsheet::Workbook.new

Add a Worksheet and you‘re good to go:

  sheet1 = book.create_worksheet

This will create a Worksheet with the Name "Worksheet1". If you prefer another name, you may do either of the following:

  sheet2 = book.create_worksheet :name => 'My Second Worksheet'
  sheet1.name = 'My First Worksheet'

Now, add data to the Worksheet, using either Worksheet#[]=, Worksheet#update_row, or work directly on Row using any of the Array-Methods that modify an Array in place:

  sheet1.row(0).concat %w{Name Country Acknowlegement}
  sheet1[1,0] = 'Japan'
  row = sheet1.row(1)
  row.push 'Creator of Ruby'
  row.unshift 'Yukihiro Matsumoto'
  sheet1.row(2).replace [ 'Daniel J. Berger', 'U.S.A.',
                          'Author of original code for Spreadsheet::Excel' ]
  sheet1.row(3).push 'Charles Lowe', 'Author of the ruby-ole Library'
  sheet1.row(3).insert 1, 'Unknown'
  sheet1.update_row 4, 'Hannes Wyss', 'Switzerland', 'Author'

Add some Formatting for flavour:

  sheet1.row(0).height = 18

  format = Spreadsheet::Format.new :color => :blue,
                                   :weight => :bold,
                                   :size => 18
  sheet1.row(0).default_format = format

  bold = Spreadsheet::Format.new :weight => :bold
  4.times do |x| sheet1.row(x + 1).set_format(0, bold) end

And finally, write the Excel File:

  book.write '/path/to/output/excel-file.xls'

Modifying an existing Document

Spreadsheet has some limited support for modifying an existing Document. This is done by copying verbatim those parts of an Excel-document which Spreadsheet can‘t modify (yet), recalculating relevant offsets, and writing the data that can be changed. Here‘s what should work:

  • Adding, changing and deleting cells.
  • You should be able to fill in Data to be evaluated by predefined Formulas

Limitations:

  • Spreadsheet can only write BIFF8 (Excel97 and higher). The results of modifying an earlier version of Excel are undefined.
  • Spreadsheet does not modify Formatting at present. That means in particular that if you set the Value of a Cell to a Date, it can only be read as a Date if its Format was set correctly prior to the change.
  • Although it is theoretically possible, it is not recommended to write the resulting Document back to the same File/IO that it was read from.

And here‘s how it works:

  book = Spreadsheet.open '/path/to/an/excel-file.xls'
  sheet = book.worksheet 0
  sheet.each do |row|
    row[0] *= 2
  end
  book.write '/path/to/output/excel-file.xls'

Date and DateTime

Excel does not know a separate Datatype for Dates. Instead it encodes Dates into standard floating-point numbers and recognizes a Date-Cell by its formatting-string:

  row.format(3).number_format

Whenever a Cell‘s Format describes a Date or Time, Spreadsheet will give you the decoded Date or DateTime value. Should you need to access the underlying Float, you may do the following:

  row.at(3)

If for some reason the Date-recognition fails, you may force Date-decoding:

  row.date(3)
  row.datetime(3)

When you set the value of a Cell to a Date, Time or DateTime, Spreadsheet will try to set the cell‘s number-format to a corresponding value (one of Excel‘s builtin formats). If you have already defined a Date- or DateTime-format, Spreadsheet will use that instead. If a format has already been applied to a particular Cell, Spreadsheet will leave it untouched:

  row[4] = Date.new 1975, 8, 21
  # -> assigns the builtin Date-Format: 'M/D/YY'
  book.add_format Format.new(:number_format => 'DD.MM.YYYY hh:mm:ss')
  row[5] = DateTime.new 2008, 10, 12, 11, 59
  # -> assigns the added DateTime-Format: 'DD.MM.YYYY hh:mm:ss'
  row.set_format 6, Format.new(:number_format => 'D-MMM-YYYY')
  row[6] = Time.new 2008, 10, 12
  # -> the Format of cell 6 is left unchanged.

More about Encodings

Spreadsheet assumes it‘s running on Ruby 1.8 with Iconv-support. It is your responsibility to handle Conversion Errors, or to prevent them e.g. by using the Iconv Transliteration and Ignore flags: Spreadsheet.client_encoding = ‘LATIN1//TRANSLIT//IGNORE‘

Backward Compatibility

Spreadsheet is designed to be a drop-in replacement for both ParseExcel and Spreadsheet::Excel. It provides a number of require-paths for backward compatibility with its predecessors. If you have been working with ParseExcel, you have probably used one or more of the following:

  require 'parseexcel'
  require 'parseexcel/parseexcel'
  require 'parseexcel/parser'

Either of the above will define the ParseExcel.parse method as a facade to Spreadsheet.open. Additionally, this will alter Spreadsheets behavior to define the ParseExcel::Worksheet::Cell class and fill each parsed Row with instances thereof, which in turn provide ParseExcel‘s Cell#to_s(encoding) and Cell#date methods. You will have to manually uninstall the parseexcel library.

If you are upgrading from Spreadsheet::Excel, you were probably using Workbook#add_worksheet and Worksheet#write, write_row or write_column. Use the following to load the code which provides them:

  require 'spreadsheet/excel'

Again, you will have to manually uninstall the spreadsheet-excel library.

If you perform fancy formatting, you may run into trouble as the Format implementation has changed considerably. If that is the case, please drop me a line at hannes.wyss@gmail.com and I will try to help you. Don‘t forget to include the offending code-snippet!

All compatibility code is deprecated and will be removed in version 1.0.0

分享到:
评论

相关推荐

    SpreadSheet控件主要属性、方法和事件

    ### SpreadSheet 控件主要属性、方法和事件 #### 一、概述 SpreadSheet 控件作为 Office Web 组件的一部分,广泛应用于各种需要展示和编辑表格数据的网页应用中。该控件的功能强大,提供了丰富的属性、方法及事件...

    OWC中SpreadSheet控件的操作方法集合

    ### OWC中SpreadSheet控件的操作方法集合 在OWC(Open Web Clent)系统中,SpreadSheet控件被广泛应用于实现类似Excel的功能,为用户提供一个直观的数据处理平台。本文档将详细介绍如何通过代码操作SpreadSheet控件...

    GemBox.Spreadsheet.Examples-master_GEM_TheMaster_

    【标题】"GemBox.Spreadsheet.Examples-master_GEM_TheMaster_" 提供了一组示例,展示了如何使用 GemBox.Spreadsheet 库在 .NET 应用程序中操作电子表格。这个库是一个强大的组件,它允许开发人员以编程方式创建、...

    phpSpreadsheet.zip

    - 使用`IOFactory::load()`方法加载Excel文件,并获取工作簿对象: ```php $spreadsheet = IOFactory::load('path_to_your_file.xlsx'); $worksheet = $spreadsheet->getActiveSheet(); ``` - 然后,你可以遍历...

    owc11 Spreadsheet 详细使用

    本篇文章将深入探讨OWC11 Spreadsheet的功能、使用方法以及常见操作,帮助用户充分利用这一工具提升工作效率。 ### 1. **基本功能** - **创建工作簿**:用户可以快速创建新的空白工作簿或基于模板的新工作簿。 - *...

    电子表格:ywesee GmbH的Ruby Spreadsheet

    试算表 入门 邮件列表可以在这里找到: 该代码可以在这里找到: 有关非GPLv3商业许可,请参阅: XLS二进制文件 描述 电子表格库旨在读取和写入电子表格文档。... 在Ruby 1.9.3中使用电子表格时,您

    关于Spreadsheet 对象的方法、事件、属性

    了解并熟练使用Spreadsheet对象的方法、事件和属性对于编写自动化脚本、集成系统或构建数据分析应用至关重要。例如,你可以通过方法来读取和写入数据,利用事件来响应用户操作,设置属性来定制界面和行为。掌握这些...

    VBA_ 使用spreadsheet控件.rar

    本资源“VBA_ 使用spreadsheet控件.rar”显然提供了一些关于如何在VBA项目中利用此控件的教程或代码示例。以下是对这个主题的详细讲解: 1. **什么是Spreadsheet控件?** Spreadsheet控件,也被称为MSForms.Data...

    Ruby-SpreadsheetArchitect可以将任何activerecord关系或ruby对象集合转换成XLSXODS或CSV电子表格

    安装可以通过RubyGems完成,只需在命令行输入`gem install spreadsheet_architect`。 一旦安装完成,你可以开始使用这个库。以下是一个简单的例子,展示如何将一个ActiveRecord模型的集合转换为CSV文件: ```ruby ...

    SpreadSheet

    下面将详细解释`SpreadSheet.cpp`和`SpreadSheet.h`这两个关键文件以及如何在VC++中操作Excel的知识点。 `SpreadSheet.cpp`和`SpreadSheet.h`是C++源代码文件,它们一起定义了一个类或一组功能,以便于程序员可以...

    C#中spreadsheet的使用

    ### C#中Spreadsheet的使用详解 在C#开发中,处理Excel文件是非常常见的需求之一。本文档将详细介绍如何在C#中使用Spreadsheet技术来读取、操作和展示Excel文件的内容。 #### 一、环境准备与前置知识 在开始之前...

    Perl SpreadSheet_Excel

    使用 `Spreadsheet::ParseExcel` 的典型代码示例可能如下: ```perl use strict; use warnings; use Spreadsheet::ParseExcel; my $parser = Spreadsheet::ParseExcel->new(); my $workbook = $parser->parse('...

    SpreadSheet简单使用实例

    1、SpreadSheet是一个Excel操作封装类,使用起来比其他的更为方便。 2、修正了原版SpreadSheet几个错误问题 3、压缩包里面包含了SpreadSheet的简单使用示例。 4、使用vs2008编译通过

    perl Spreadsheet

    - 访问工作表:使用`workheets()`方法获取Workbook中的所有工作表,然后通过`worksheet()`方法选择特定工作表。 - 读取数据:`get_cell()`方法用于读取指定位置的单元格内容,或者遍历整个工作表获取所有数据。 -...

    DevExpress SpreadSheet 报表模板演示源码

    5. **公式和计算**:SpreadSheetControl提供了与Excel兼容的公式引擎,允许在报表模板中使用各种数学、统计和逻辑公式。 6. **图表创建**:可以创建各种类型的图表,如柱状图、折线图、饼图等,用于数据分析和可视...

    vc—spreadsheet 11.0 使用

    解决这类问题通常需要查看头文件和库文档,确认接口的使用方法。 6. **调试和测试**:在解决了编译问题后,进行充分的调试和测试以确保功能正常。可以使用VS C++ 6.0的调试器来跟踪代码执行,检查变量状态,定位...

    excel lib ror ruby

    `ruby-ole-1.2.11.4.gem` 文件是这个库的安装包,可以使用Ruby的gem管理器进行安装。 4. **example.txt**: 这可能是一个包含使用这些库的示例代码或教程的文本文件。实际应用中,开发者会参考这样的示例来学习如何...

    ThinkPHP5.1 框架下 PhpSpreadsheet 操作 Excel 表的导入导出.rar

    2. **读取文件**: 使用`\PhpOffice\PhpSpreadsheet\IOFactory`类的`load`方法加载Excel文件。 3. **遍历数据**: 获取工作表并逐行读取数据,可以使用`getActiveSheet`获取当前活动工作表,然后通过`getRowIterator`...

    简单电子表格:简单电子表格是Ruby Gem阅读器,适用于常见电子表格格式:Excel(.xls,.xlsx),Open-office(.ods)和CSV(标准,excel,制表符分隔)

    gem 'simple-spreadsheet' 然后执行: $ bundle install 功能性 阅读电子表格 例子: require "simple-spreadsheet" s = SimpleSpreadsheet :: Workbook . read ( "my_spreadsheets_file.xls" ) 支持的格式: ...

    PhpSpreadsheet-master.zip

    本文将深入探讨PhpSpreadsheet的核心功能及其使用方法。 首先,我们需要了解什么是PhpSpreadsheet。PhpSpreadsheet是PHP Office项目的一部分,它取代了之前的PHPExcel库,提供了更优化的性能和更多的功能。这个库...

Global site tag (gtag.js) - Google Analytics