ExcelからSVGを生成(Python版)
Pythonの勉強のため、以前にPHP + PhpSpeadsheetで作成したプログラムをPyhon + OpenPyXLでも作成してみました。
ソースコードの量は、PHPよりも少しだけ多くなってしまいましたが、このくらいなら許容範囲。
PHPだとHTMLにプログラムを埋め込んでいる感じだけど、Pythonだと"print"でHTMLを出力させている感じになる。
個人的にはWebアプリケーションを作るのなら、PHPを使いたいところ。
※ |
実は最初に"xlrd"というライブラリも試してみたけど、値が入った一番右下のセルまでしかアクセスできないので、今回のように値が全く入っていないシートを対象にするプログラムには不向きみたい。 |
■Pyhon + OpenPyXLのソースコード(Python Ver38-32, OpenPyXL Ver3.0.2で動作を確認)
index.py
# coding: UTF-8
import cgi
import cgitb
import io
import openpyxl
import openpyxl.styles
import re
def getCellColor(cell):
if cell.fill is None:
return None
if cell.fill.start_color is None:
return None
if cell.fill.start_color.rgb is None:
return None
if not re.match('^[0-9A-F]{8}$', cell.fill.start_color.rgb):
return None
if cell.fill.start_color.rgb[:2] == '00':
return None
else:
return cell.fill.start_color.rgb[2:]
cgitb.enable()
form = cgi.FieldStorage()
svg = ''
if 'file_name' in form:
upload = form['file_name']
if upload.file:
book = openpyxl.load_workbook(upload.file)
sheet = book.worksheets[0]
svg = '<svg xmlns="http://www.w3.org/2000/svg" width="' + str(18 * 16) + '" height="' + str(18 * 16) + '" version="1.1">\n'
for row in range(16):
for column in range(16):
cell = sheet.cell(row + 1, column + 1)
color = getCellColor(cell)
if color is not None:
svg += ' <rect x="' + str(18 * column) + '" y="' + str(18 * row) + '" width="18" height="18" stroke="none" fill="#' + color + '" />\n'
svg += '</svg>\n'
print('Status: 200 OK')
print('Content-Type: text/html; charset=utf-8')
print()
html = """
<!DOCTYPE html>
<html>
<body>
<form action="./index.py" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="file" name="file_name" value="" accept=".xlsx,application/msexcel" required /></td>
<td style="text-align:left; width:100%;"><input type="submit" value="Upload" /></td>
</tr>
<tr>
<td>Preview</td>
</tr>
<tr>
<td colspan="2">
<div style="width:288px; height:288px; background-color:#f0f0f0">
"""
html += svg
html += """
</div>
</td>
</tr>
<tr>
<td>HTML</td>
</tr>
<tr>
<td colspan="2">
<textarea style="width:720px; height:300px; background-color:black; color:white;">
"""
html += svg
html += """
</textarea>
</td>
</tr>
</table>
</form>
</body>
</html>
"""
print(html)
戻る