| 1 |
from trac.wiki.macros import WikiMacroBase |
|---|
| 2 |
from trac.util import escape |
|---|
| 3 |
from StringIO import StringIO |
|---|
| 4 |
import csv |
|---|
| 5 |
|
|---|
| 6 |
class CsvMacro(WikiMacroBase): |
|---|
| 7 |
""" |
|---|
| 8 |
Display CSV data in a table. Simply copy and paste the CSV data into the macro body and hope for the best. |
|---|
| 9 |
|
|---|
| 10 |
Example: |
|---|
| 11 |
{{{ |
|---|
| 12 |
{{{ |
|---|
| 13 |
#!CSV |
|---|
| 14 |
123 123 123 123 |
|---|
| 15 |
234 234 234 234 |
|---|
| 16 |
}}} |
|---|
| 17 |
}}} |
|---|
| 18 |
Renders as |
|---|
| 19 |
|
|---|
| 20 |
|| 123 || 123 || 123 || 123 || |
|---|
| 21 |
|| 234 || 234 || 234 || 234 || |
|---|
| 22 |
""" |
|---|
| 23 |
|
|---|
| 24 |
def get_macros(self): |
|---|
| 25 |
yield 'CSV' |
|---|
| 26 |
|
|---|
| 27 |
def expand_macro(self, formatter, name, txt): |
|---|
| 28 |
sniffer = csv.Sniffer() |
|---|
| 29 |
txt = txt.encode('ascii', 'replace') |
|---|
| 30 |
reader = csv.reader(StringIO(txt), sniffer.sniff(txt)) |
|---|
| 31 |
formatter.out.write('<table class="wiki">\n') |
|---|
| 32 |
for row in reader: |
|---|
| 33 |
formatter.out.write('<tr>') |
|---|
| 34 |
for col in row: |
|---|
| 35 |
formatter.out.write('<td>%s</td>' % escape(col)) |
|---|
| 36 |
formatter.out.write('</tr>\n') |
|---|
| 37 |
formatter.out.write('</table>\n') |
|---|