Browse Source

added an excel to markdown table converter

master
Holger Frey 4 years ago
parent
commit
bc7ec1bb54
  1. 1
      pyproject.toml
  2. 56
      work_helpers/excel2markdown.py

1
pyproject.toml

@ -20,5 +20,6 @@ requires = [
[tool.flit.scripts] [tool.flit.scripts]
xls2changelog = "work_helpers.excel2changelog:cli" xls2changelog = "work_helpers.excel2changelog:cli"
xls2markdown = "work_helpers.excel2markdown:cli"
sg_mbp_release = "work_helpers.sg_mbp_release:sg_mbp_release" sg_mbp_release = "work_helpers.sg_mbp_release:sg_mbp_release"
sg_mbp_new_version = "work_helpers.sg_mbp_release:sg_mbp_new_version" sg_mbp_new_version = "work_helpers.sg_mbp_release:sg_mbp_new_version"

56
work_helpers/excel2markdown.py

@ -0,0 +1,56 @@
import click
import pyperclip
def split_table(text):
rows = []
for line in text.splitlines():
values = line.split("\t")
cells = [v.strip() for v in values]
rows.append(cells)
return rows
def get_cell_lengths(table):
tmp = { }
for row in table:
for i, cell in enumerate(row):
if i not in tmp:
tmp[i] = []
tmp[i].append(len(cell))
return {k: max(v) for k, v in tmp.items()}
def build_table(table, lengths):
text_rows = [_build_row(row, lengths) for row in table]
header, *rest = text_rows
sep_items = [
"-" * lengths[k] for k in sorted(lengths.keys())
]
separator = _build_line(sep_items)
lines = [header, separator] + rest
return "\r\n".join(lines)
def _build_row(row, lengths):
items = []
for i, cell in enumerate(row):
length = lengths[i]
items.append(cell.ljust(length))
return _build_line(items)
def _build_line(items):
tmp = " | ".join(items)
return f"| {tmp} |"
@click.command()
def cli():
xls = pyperclip.paste()
table = split_table(xls)
lengths = get_cell_lengths(table)
result = build_table(table, lengths)
print("copied to clipboard")
pyperclip.copy(result)
Loading…
Cancel
Save