49 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Merge Jushuitan XLSX export parts without loading a whole file into memory."""
import sys
from openpyxl import Workbook, load_workbook
def main() -> int:
if len(sys.argv) < 4:
print("用法:merge-xlsx.py <输出.xlsx> <输入1.xlsx> <输入2.xlsx> ...", file=sys.stderr)
return 2
destination, *sources = sys.argv[1:]
workbook = Workbook(write_only=True)
sheet = workbook.create_sheet("账单明细")
header = None
rows_written = 0
for source in sources:
source_book = load_workbook(source, read_only=True, data_only=True)
try:
source_sheet = source_book.worksheets[0]
iterator = source_sheet.iter_rows(values_only=True)
source_header = next(iterator, None)
if source_header is None:
raise ValueError(f"{source} 没有表头")
source_header = ["" if value is None else str(value).strip() for value in source_header]
if header is None:
header = source_header
sheet.append(header)
elif source_header != header:
raise ValueError(f"{source} 的表头与其他分片不一致")
for values in iterator:
if values is None or not any(str(value).strip() for value in values if value is not None):
continue
sheet.append(list(values))
rows_written += 1
finally:
source_book.close()
workbook.save(destination)
print(f"xlsx={destination} rows={rows_written} parts={len(sources)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())