Class: GoogleSpreadsheet::Worksheet

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/google_spreadsheet.rb

Overview

Use GoogleSpreadsheet::Spreadsheet#worksheets to get GoogleSpreadsheet::Worksheet object.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Util

encode_query, h, http_request, uri_encode

Constructor Details

#initialize(session, cells_feed_url, title = nil) ⇒ Worksheet

:nodoc:



290
291
292
293
294
295
296
297
# File 'lib/google_spreadsheet.rb', line 290

def initialize(session, cells_feed_url, title = nil) #:nodoc:
  @session = session
  @cells_feed_url = cells_feed_url
  @title = title
  @cells = nil
  @input_values = nil
  @modified = Set.new()
end

Instance Attribute Details

#cells_feed_urlObject (readonly)

URL of cell-based feed of the spreadsheet.



300
301
302
# File 'lib/google_spreadsheet.rb', line 300

def cells_feed_url
  @cells_feed_url
end

Instance Method Details

#[](row, col) ⇒ Object

Returns content of the cell as String. Top-left cell is [1, 1].



303
304
305
# File 'lib/google_spreadsheet.rb', line 303

def [](row, col)
  return self.cells[[row, col]] || ""
end

#[]=(row, col, value) ⇒ Object

Updates content of the cell. Note that update is not sent to the server until you call save(). Top-left cell is [1, 1].

e.g.

worksheet[2, 1] = "hoge"
worksheet[1, 3] = "=A1+B1"


314
315
316
317
318
319
320
321
# File 'lib/google_spreadsheet.rb', line 314

def []=(row, col, value)
  reload() if !@cells
  @cells[[row, col]] = value
  @input_values[[row, col]] = value
  @modified.add([row, col])
  self.max_rows = row if row > @max_rows
  self.max_cols = col if col > @max_cols
end

#cellsObject

:nodoc:



383
384
385
386
# File 'lib/google_spreadsheet.rb', line 383

def cells #:nodoc:
  reload() if !@cells
  return @cells
end

#dirty?Boolean

Returns true if you have changes made by []= which haven’t been saved.

Returns:

  • (Boolean)


521
522
523
# File 'lib/google_spreadsheet.rb', line 521

def dirty?
  return !@modified.empty?
end

#input_value(row, col) ⇒ Object

Returns the value or the formula of the cell. Top-left cell is [1, 1].

If user input “=A1+B1” to cell [1, 3], worksheet[1, 3] is “3” for example and worksheet.input_value(1, 3) is “=RC+RC”.



327
328
329
330
# File 'lib/google_spreadsheet.rb', line 327

def input_value(row, col)
  reload() if !@cells
  return @input_values[[row, col]] || ""
end

#max_colsObject

Number of columns including empty columns.



358
359
360
361
# File 'lib/google_spreadsheet.rb', line 358

def max_cols
  reload() if !@cells
  return @max_cols
end

#max_cols=(cols) ⇒ Object

Updates number of columns. Note that update is not sent to the server until you call save().



365
366
367
368
# File 'lib/google_spreadsheet.rb', line 365

def max_cols=(cols)
  @max_cols = cols
  @meta_modified = true
end

#max_rowsObject

Number of rows including empty rows.



345
346
347
348
# File 'lib/google_spreadsheet.rb', line 345

def max_rows
  reload() if !@cells
  return @max_rows
end

#max_rows=(rows) ⇒ Object

Updates number of rows. Note that update is not sent to the server until you call save().



352
353
354
355
# File 'lib/google_spreadsheet.rb', line 352

def max_rows=(rows)
  @max_rows = rows
  @meta_modified = true
end

#num_colsObject

Column number of the right-most non-empty column.



339
340
341
342
# File 'lib/google_spreadsheet.rb', line 339

def num_cols
  reload() if !@cells
  return @cells.keys.map(){ |r, c| c }.max || 0
end

#num_rowsObject

Row number of the bottom-most non-empty row.



333
334
335
336
# File 'lib/google_spreadsheet.rb', line 333

def num_rows
  reload() if !@cells
  return @cells.keys.map(){ |r, c| r }.max || 0
end

#reloadObject

Reloads content of the worksheets from the server. Note that changes you made by []= is discarded if you haven’t called save().



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/google_spreadsheet.rb', line 401

def reload()
  doc = @session.get(@cells_feed_url)
  @max_rows = doc.search("gs:rowCount").text.to_i()
  @max_cols = doc.search("gs:colCount").text.to_i()
  @title = doc.search("title").text
  @cells = {}
  @input_values = {}
  for entry in doc.search("entry")
    cell = entry.search("gs:cell")[0]
    row = cell["row"].to_i()
    col = cell["col"].to_i()
    @cells[[row, col]] = cell.inner_text
    @input_values[[row, col]] = cell["inputValue"]
  end
  @modified.clear()
  @meta_modified = false
  return true
end

#rows(skip = 0) ⇒ Object

An array of spreadsheet rows. Each row contains an array of columns. Note that resulting array is 0-origin so worksheet.rows[0] == worksheet[1, 1].



391
392
393
394
395
396
397
# File 'lib/google_spreadsheet.rb', line 391

def rows(skip = 0)
  nc = self.num_cols
  result = ((1 + skip)..self.num_rows).map() do |row|
    (1..nc).map(){ |col| self[row, col] }.freeze()
  end
  return result.freeze()
end

#saveObject

Saves your changes made by []= to the server.



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/google_spreadsheet.rb', line 421

def save()
  sent = false
  
  if @meta_modified
    
    # I don't know good way to get worksheet feed URL from cells feed URL.
    # Probably it would be cleaner to keep worksheet feed URL and get cells feed URL
    # from it.
    if !(@cells_feed_url =~
        %r{^http://spreadsheets.google.com/feeds/cells/(.*)/(.*)/private/full$})
      raise(GoogleSpreadsheet::Error,
        "cells feed URL is in unknown format: #{@cells_feed_url}")
    end
    ws_doc = @session.get(
      "http://spreadsheets.google.com/feeds/worksheets/#{$1}/private/full/#{$2}")
    edit_url = ws_doc.search("link[@rel='edit']")[0]["href"]
    xml = "      <entry xmlns='http://www.w3.org/2005/Atom'\n             xmlns:gs='http://schemas.google.com/spreadsheets/2006'>\n        <title>\#{h(@title)}</title>\n        <gs:rowCount>\#{h(@max_rows)}</gs:rowCount>\n        <gs:colCount>\#{h(@max_cols)}</gs:colCount>\n      </entry>\n    EOS\n    @session.put(edit_url, xml)\n    \n    @meta_modified = false\n    sent = true\n    \n  end\n  \n  if [email protected]?\n    \n    # Gets id and edit URL for each cell.\n    # Note that return-empty=true is required to get those info for empty cells.\n    cell_entries = {}\n    rows = @modified.map(){ |r, c| r }\n    cols = @modified.map(){ |r, c| c }\n    url = \"\#{@cells_feed_url}?return-empty=true&min-row=\#{rows.min}&max-row=\#{rows.max}\" +\n      \"&min-col=\#{cols.min}&max-col=\#{cols.max}\"\n    doc = @session.get(url)\n    for entry in doc.search(\"entry\")\n      row = entry.search(\"gs:cell\")[0][\"row\"].to_i()\n      col = entry.search(\"gs:cell\")[0][\"col\"].to_i()\n      cell_entries[[row, col]] = entry\n    end\n    \n    # Updates cell values using batch operation.\n    xml = <<-\"EOS\"\n      <feed xmlns=\"http://www.w3.org/2005/Atom\"\n            xmlns:batch=\"http://schemas.google.com/gdata/batch\"\n            xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">\n        <id>\#{h(@cells_feed_url)}</id>\n    EOS\n    for row, col in @modified\n      value = @cells[[row, col]]\n      entry = cell_entries[[row, col]]\n      id = entry.search(\"id\").text\n      edit_url = entry.search(\"link[@rel='edit']\")[0][\"href\"]\n      xml << <<-\"EOS\"\n        <entry>\n          <batch:id>\#{h(row)},\#{h(col)}</batch:id>\n          <batch:operation type=\"update\"/>\n          <id>\#{h(id)}</id>\n          <link rel=\"edit\" type=\"application/atom+xml\"\n            href=\"\#{h(edit_url)}\"/>\n          <gs:cell row=\"\#{h(row)}\" col=\"\#{h(col)}\" inputValue=\"\#{h(value)}\"/>\n        </entry>\n      EOS\n    end\n    xml << <<-\"EOS\"\n      </feed>\n    EOS\n    result = @session.post(\"\#{@cells_feed_url}/batch\", xml)\n    for entry in result.search(\"atom:entry\")\n      interrupted = entry.search(\"batch:interrupted\")[0]\n      if interrupted\n        raise(GoogleSpreadsheet::Error, \"Update has failed: %s\" %\n          interrupted[\"reason\"])\n      end\n      if !(entry.search(\"batch:status\")[0][\"code\"] =~ /^2/)\n        raise(GoogleSpreadsheet::Error, \"Updating cell %s has failed: %s\" %\n          [entry.search(\"atom:id\").text, entry.search(\"batch:status\")[0][\"reason\"]])\n      end\n    end\n    \n    @modified.clear()\n    sent = true\n    \n  end\n  return sent\nend\n"

#synchronizeObject

Calls save() and reload().



515
516
517
518
# File 'lib/google_spreadsheet.rb', line 515

def synchronize()
  save()
  reload()
end

#titleObject

Title of the worksheet (shown as tab label in Web interface).



371
372
373
374
# File 'lib/google_spreadsheet.rb', line 371

def title
  reload() if !@title
  return @title
end

#title=(title) ⇒ Object

Updates title of the worksheet. Note that update is not sent to the server until you call save().



378
379
380
381
# File 'lib/google_spreadsheet.rb', line 378

def title=(title)
  @title = title
  @meta_modified = true
end