CSV(TSV)から、HTMLテーブルに変換するサービスを作りました。デザイン調整などまだできていないので、かっこ悪いのですが、動作自体は安定していると思います。お約束のソースコードは記事の末尾に添付してます。
サービスの使い方
一番上のテキストエリアに、CSV(カンマ区切りデータ)もしくは、TSV(タブ区切りデータ)を入力して変換ボタンをクリックしてください。HTMLテーブルのプレビューと、そのソースコードが表示されます。CSVなのか、TSVなのかは、自動判別されます。
スクリーンショット
以下の画像をクリックすると、サービスのURLにジャンプします。
ソースコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | #!/usr/bin/env python # -*- coding: utf-8 -*- from google.appengine.ext import webapp from google.appengine.ext.webapp import util import cgi class MainHandler(webapp.RequestHandler): def get(self): if self.request.get("csv"): csv = self.request.get("csv") else: csv = """0,1,2,3 1,1,2,3 2,2,4,6""" html = getCss() + getTable(csv) self.response.out.write(u""" <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>CSV2Table TSV2Table</title> </head> <body> <center> <h1>CSV2Table</h1> エクセルなどで作成したCSVやTSVをHTMLテーブルに変換するサービスです。 <form method="post"><input type="hidden" name="phpMyAdmin" value="cfc2644bd9c947213a0141747c2608b0" /> <div><textarea name="csv" style="width:500px;height:200px">%s</textarea></div> <input type="submit" value="変換"/> <div>%s</div> <div><textarea style="width:500px;height:500px">%s</textarea></div> </form> Powered By <a href="http://php6.jp/python">python練習帳</a> </center> </body> </html> """ % ( csv, html, cgi.escape(html))) def post(self): self.get() def getCss(): return """ <style> .pytb { margin:0px 0px 10px 0px;padding:0px; border-collapse:collapse; } .pytb th { padding:4px 2px 2px 4px; text-align:left;vertical-align:top;color:#3366CC; background-color:#99CCFF; border:1px solid #6699CC; } .pytb td { padding:4px 2px 2px 4px; background-color:#EEEEEE; border:1px solid #6699CC; } </style> """ def getTable(csv): table = [] sep = getSeperator(csv) for line in csv.strip().split("\n"): tr = [] for value in line.split(sep): tr.append(cgi.escape(value.strip())) table.append(tr) html = "" for i, tr in enumerate(table): subhtml = "" for j, value in enumerate(tr): if i: if j: subhtml = subhtml + "<td>" + value + "</td>\n" else: subhtml = subhtml + '<th class="first_row">' + value + "</td>\n" else: if j: subhtml = subhtml + '<th class="first_column">' + value + "</th>\n" else: subhtml = subhtml + '<th class="first_row first_column">' + value + "</th>\n" html = html + "<tr>\n" + subhtml + "</tr>\n" html = '<table class="pytb">\n' + html + "</table>" return html def getSeperator(csv): max = 0 candidates = ["\t",","] sep = "," for s in candidates: tmp = csv.count(s) if tmp > max: max = tmp sep = s return sep def main(): application = webapp.WSGIApplication([('/', MainHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main() |