DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Excel To GraphViz RDF Converter

12.08.2010
| 3738 views |
  • submit to reddit
        // Excel to GraphViz RDF Converter *Ruby*

#!/usr/bin/env ruby -W0 
# =============================================================================
#       File: excel2dot.rb
# Decription: utility to convert RDF triples listed in Excel to GraphViz "dot"
#             formatted files.
#      Usage: ./excel2dot InFile.xls  OutFile[.dot] graph_name graph_dir
#           : InFile.xls - File with 3 columns (first row is skipped)
#           : OutFile[.dot] Output file in GraphViz DOT format
#           : graph_name - any textname (no spaces) for the Digraph name
#           : graph_dir  - "v" top-down oriented, "h" left to right oriented 
#    Version: 0.2
# =============================================================================
require 'rubygems'
require 'spreadsheet'

numArgs = ARGV.count

# Check to ensure that we have at least 2 arguments (input and output file)
if numArgs < 2
  puts "Usage: ./excel2dot RDF_TriplesSpreadsheet.xls GraphVizDotFile[.vg] graph_name graph_dir"
else

  if numArgs < 3
    GraphName = "my_graph"
  else
    GraphName = ARGV[2].to_s
  end

  # Default to Horizontal Graphing unless specified
  if numArgs < 4
    GraphDir = "h"
  else
    GraphDir = ARGV[3].to_s.downcase
  end

#    puts "Number of Args: " + ARGV.count.to_s 
#    puts "Spreadsheet File:" + ARGV[0] 
#    puts "GraphViz Dot File:" + ARGV[1]
    puts "Coverting Spreadsheet Triples to Dot..."

    # Open Input Triples Excel Spreadsheet 
    book = Spreadsheet.open ARGV[0]

    # Open Output GraphViz Dot File 
    gvdFile = File.new(ARGV[1],"w")

    # Write header for dot file
    gvdFile.puts "digraph #{GraphName} {"

    sheet = book.worksheet 0
      sheet.each(skip=1) do |row|
        gvdFile.puts "\t"+ "\"#{row[0].strip}\"" + "\t-> " + "\"#{row[2].strip}\"" + "\t[label=" + "\"#{row[1].strip}\"];"

        # if the short name predicate is encountered then change the color and shape of the graphic item for the video name
        if row[1].strip == "video:short_name"
           gvdFile.puts "\t\"#{row[2].strip}\"" + "\t[shape=polygon,sides=8,peripheries=2,color=purple,style=filled];"
        end
      end

    # Set up the graphing flow direction
    if (GraphDir == "h")  || (GraphDir != "v")
      gvdFile.puts "\trankdir=LR"
    end

    gvdFile.puts "}"
    gvdFile.close
    puts "Done!"
end