Files

104 lines
3.2 KiB
Python
Raw Permalink Normal View History

2026-06-29 15:32:32 +08:00
import json
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
def json_to_excel(json_file_path, output_excel_path=None):
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
if output_excel_path is None:
output_excel_path = json_file_path.rsplit('.', 1)[0] + '.xlsx'
wb = Workbook()
thin_border = Border(
left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin')
)
data_field = data.get('Data', {})
if isinstance(data_field, str):
data_field = json.loads(data_field)
tables_info = data_field.get('prism_tablesInfo', [])
for idx, table in enumerate(tables_info):
if idx == 0:
ws = wb.active
ws.title = f"Table_{table.get('tableId', idx)}"
else:
ws = wb.create_sheet(title=f"Table_{table.get('tableId', idx)}")
x_cell_size = table.get('xCellSize', 0)
y_cell_size = table.get('yCellSize', 0)
cell_infos = table.get('cellInfos', [])
grid = {}
for cell in cell_infos:
xsc = cell.get('xsc', 0)
ysc = cell.get('ysc', 0)
xec = cell.get('xec', xsc)
yec = cell.get('yec', ysc)
word = str(cell.get('word', ''))
key = (ysc, xsc)
grid[key] = {
'word': word,
'xsc': xsc,
'xec': xec,
'ysc': ysc,
'yec': yec,
}
for cell_info in cell_infos:
xsc = cell_info.get('xsc', 0)
ysc = cell_info.get('ysc', 0)
xec = cell_info.get('xec', xsc)
yec = cell_info.get('yec', ysc)
word = str(cell_info.get('word', ''))
row_start = ysc + 1
col_start = xsc + 1
row_end = yec + 1
col_end = xec + 1
ws.cell(row=row_start, column=col_start, value=word)
if xec > xsc or yec > ysc:
ws.merge_cells(
start_row=row_start,
start_column=col_start,
end_row=row_end,
end_column=col_end,
)
for r in range(row_start, row_end + 1):
for c in range(col_start, col_end + 1):
cell_obj = ws.cell(row=r, column=c)
cell_obj.border = thin_border
cell_obj.alignment = Alignment(
horizontal='center',
vertical='center',
wrap_text=True,
)
cell_obj.font = Font(name='Arial', size=10)
from openpyxl.utils import get_column_letter
for c in range(1, x_cell_size + 1):
ws.column_dimensions[get_column_letter(c)].width = 15
wb.save(output_excel_path)
return output_excel_path
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
print('Usage: python json_to_excel.py <input.json> [output.xlsx]')
sys.exit(1)
json_path = sys.argv[1]
out_path = sys.argv[2] if len(sys.argv) > 2 else None
2026-06-29 15:32:32 +08:00
result = json_to_excel(json_path, out_path)
print(f"Excel saved to: {result}")