Skip to content

Instantly share code, notes, and snippets.

@KatsuhiroMorishita
Created August 24, 2017 03:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KatsuhiroMorishita/91b3a15254a6d3b2709cd8c6051ce66f to your computer and use it in GitHub Desktop.
Save KatsuhiroMorishita/91b3a15254a6d3b2709cd8c6051ce66f to your computer and use it in GitHub Desktop.
Excelの表からhtmlのtableを作成するPythonのスクリプトです。縦に結合したセルがあっても大丈夫です。(横に結合したセルがあると対応できない)
# Excelの表からhtmlのtableを作成する
# memo: 体育大会の試合結果をWebに掲載するために作成した。
# author: Katsuhiro Morishita
# created: 2017-08-24
# lisence: MIT
import pandas as pd
import math
import re
# Excelファイルを開く
df = pd.read_excel("kyushu_yatsushiro.xlsx") # ファイル名は多分半角英数のみ対応
print(df)
# テキストファイルに書き出す
with open("out.html", "w", encoding="utf-8-sig") as fw:
# ヘッダ部分の書き込み
fw.write("""
<html lang="ja" data-scribe-reduced-action-queue="true">
<head>
<meta charset="utf-8">
<style type="text/css">
@import url( http://www.kumamoto-nct.ac.jp/wp/wp-content/themes/KumamotoNCT-201006/style.css?20151130 );
</style>
</head>\n""")
# 以降、tableの書き出し
fw.write('<table class="line-table centering" width=100%>\n')
# 項目名の書き出し
fw.write("\t<tr>\n")
for index in df.columns:
fw.write('\t\t<th>{0}</th>\n'.format(index))
fw.write("\t</tr>\n")
# 表の中身の書き出し
for i in range(len(df)):
fw.write("\t<tr>\n")
# print("--row", df.iloc[i, :], "--") # 1レコード分のデータ
for k in range(len(df.columns)):
val = df.iloc[i, k]
rowspan = 1
print(val, type(val))
if isinstance(val, str): # rowspanの計数
val = re.sub("(\r\n)|(\n)", "<br />", val) # 改行コードはタグに置換
l = 1
while i+l < len(df):
_val = df.iloc[i+l, k]
#print("--", _val)
if isinstance(_val, str):
break
l += 1
rowspan = l
#print("rowspan", rowspan)
fw.write('\t\t<td colspan="1" rowspan="{0}">{1}</td>\n'.format(rowspan, val))
fw.write("\t</tr>\n")
fw.write("</table>\n")
fw.write("</html>\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment