diff --git a/controllers/plugin_dbui.py b/controllers/plugin_dbui.py
index 5c922ad6b2cb8531a8f89b9b80d27f4b7eeba332..1d17706587a90bb62cf9d99170d5e6dd22926324 100644
--- a/controllers/plugin_dbui.py
+++ b/controllers/plugin_dbui.py
@@ -15,18 +15,11 @@ __version__ = "$Revision$"
 
 
 import os
-import traceback
-import sys
-
-
-from gluon.contrib import simplejson as json
-from gluon.http import HTTP
-from gluon.tools import PluginManager
-from pprint import pprint
 
 
 SCRIPT = """
 Ext.namespace('App');
+App.csvUrl = '/%s/plugin_dbui/csv';
 App.name = '%s';
 App.REMOTE_API = {
     'url': '/%s/plugin_dbui/call',
@@ -44,6 +37,44 @@ def call():
     return directSvc()
 
 
+def csv():
+    """Controller returning the content of a table as a CSV file.
+    Foreign keys are replaced by the parent column.
+    
+    """
+    import gluon.contenttype
+    dbui = local_import('plugin_dbui')
+
+    response.headers['Content-Type'] = gluon.contenttype.contenttype('.csv')
+    response.headers['Content-Disposition'] = 'attachment; filename=foo.csv;'
+    
+    table = request.vars['tableName']
+    query = db[table].id > 0
+    
+    # replace foreign key by parent fields
+    # and build the query to resolve foreign keys
+    svc = dbui.ForeignField(db)
+    if svc.is_table_with_foreign_fields(table):
+    
+        fields = []
+        query = ((query) & (svc.get_where_query(table)))
+        
+        for field in db[table].fields:
+        
+            if svc.is_foreign_field(table, field):
+                k_table, k_field, k_key = svc.get_foreign_data(table, field)
+                fields.append(db[k_table][k_field])
+                
+            else:
+                fields.append(db[table][field])
+    else:
+        fields = [db[table].ALL]
+
+    # interrogate the database    
+    rows = db(query).select(*fields)
+    return str(rows)
+    
+
 def debug():
     """Main Controller to run the plugin in debug mode
     Load the javascript source code for all libraries.
@@ -112,6 +143,8 @@ def get_api():
     """Controller returning the javascript API definition.
     
     """
+    from gluon.contrib import simplejson as json
+
     di = {}
     dbui = local_import('plugin_dbui')
     
@@ -143,6 +176,7 @@ def get_api():
     # fill the javascript template
     app = request.application
     script = SCRIPT % (app, 
+                       app,
                        app, 
                        json.dumps(di),
                        json.dumps(storeCfgs),