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:



302
303
304
305
306
307
308
309
310
# File 'lib/google_spreadsheet.rb', line 302

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.



313
314
315
# File 'lib/google_spreadsheet.rb', line 313

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].



316
317
318
# File 'lib/google_spreadsheet.rb', line 316

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"


327
328
329
330
331
332
333
334
# File 'lib/google_spreadsheet.rb', line 327

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:



396
397
398
399
# File 'lib/google_spreadsheet.rb', line 396

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

#deleteObject

Deletes this worksheet



548
549
550
551
552
553
554
555
556
557
558
559
# File 'lib/google_spreadsheet.rb', line 548

def delete
  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"]
  
  @session.delete(edit_url)
end

#dirty?Boolean

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

Returns:

  • (Boolean)


562
563
564
# File 'lib/google_spreadsheet.rb', line 562

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”.



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

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

#max_colsObject

Number of columns including empty columns.



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

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().



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

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

#max_rowsObject

Number of rows including empty rows.



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

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().



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

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

#num_colsObject

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



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

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.



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

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().



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/google_spreadsheet.rb', line 414

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].



404
405
406
407
408
409
410
# File 'lib/google_spreadsheet.rb', line 404

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.



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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/google_spreadsheet.rb', line 435

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 = <<-"EOS"
      <entry xmlns='http://www.w3.org/2005/Atom'
             xmlns:gs='http://schemas.google.com/spreadsheets/2006'>
        <title>#{h(@title)}</title>
        <gs:rowCount>#{h(@max_rows)}</gs:rowCount>
        <gs:colCount>#{h(@max_cols)}</gs:colCount>
      </entry>
    EOS
    
    @session.put(edit_url, xml)
    
    @meta_modified = false
    sent = true
    
  end
  
  if !@modified.empty?
    
    # Gets id and edit URL for each cell.
    # Note that return-empty=true is required to get those info for empty cells.
    cell_entries = {}
    rows = @modified.map(){ |r, c| r }
    cols = @modified.map(){ |r, c| c }
    url = "#{@cells_feed_url}?return-empty=true&min-row=#{rows.min}&max-row=#{rows.max}" +
      "&min-col=#{cols.min}&max-col=#{cols.max}"
    doc = @session.get(url)
    for entry in doc.search("entry")
      row = entry.search("gs:cell")[0]["row"].to_i()
      col = entry.search("gs:cell")[0]["col"].to_i()
      cell_entries[[row, col]] = entry
    end
    
    # Updates cell values using batch operation.
    cells = @modified.size
    current_cell = 0
    
    while current_cell < cells
      batch_count = 0
      xml = <<-EOS
        <feed xmlns="http://www.w3.org/2005/Atom"
              xmlns:batch="http://schemas.google.com/gdata/batch"
              xmlns:gs="http://schemas.google.com/spreadsheets/2006">
          <id>#{h(@cells_feed_url)}</id>
      EOS
      
      until batch_count >= 250
        row,col = @modified[current_cell]
        value = @cells[[row, col]]
        entry = cell_entries[[row, col]]
        id = entry.search("id").text
        edit_url = entry.search("link[@rel='edit']")[0]["href"]
        xml << <<-EOS
          <entry>
            <batch:id>#{h(row)},#{h(col)}</batch:id>
            <batch:operation type="update"/>
            <id>#{h(id)}</id>
            <link rel="edit" type="application/atom+xml"
              href="#{h(edit_url)}"/>
            <gs:cell row="#{h(row)}" col="#{h(col)}" inputValue="#{h(value)}"/>
          </entry>
        EOS
        
        # close each batch out at 500 cells
        current_cell +=1
        batch_count += 1
      end
      
      xml << "</feed>"
    
      result = @session.post("#{@cells_feed_url}/batch", xml)
      for entry in result.search("atom:entry")
        interrupted = entry.search("batch:interrupted")[0]
        if interrupted
          raise(GoogleSpreadsheet::Error, "Update has failed: %s" %
            interrupted["reason"])
        end
        if !(entry.search("batch:status")[0]["code"] =~ /^2/)
          raise(GoogleSpreadsheet::Error, "Updating cell %s has failed: %s" %
            [entry.search("atom:id").text, entry.search("batch:status")[0]["reason"]])
        end
      end
    end
    
    @modified.clear()
    sent = true
    
  end
  return sent
end

#synchronizeObject

Calls save() and reload().



542
543
544
545
# File 'lib/google_spreadsheet.rb', line 542

def synchronize()
  save()
  reload()
end

#titleObject

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



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

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().



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

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