JSON을 Excel로 변환: 전체 가이드

JSON은 구조화된 데이터를 저장하고 교환하는 데 가장 널리 사용되는 형식 중 하나입니다. API, 구성 파일 및 많은 최신 응용 프로그램에서 JSON을 사용하여 데이터 세트를 나타냅니다.

그러나 JSON은 비기술적인 사용자와 분석, 보고 또는 공유하기에 항상 편리한 것은 아닙니다. 많은 경우 JSON 데이터를 Excel 스프레드시트로 변환하면 정보를 더 쉽게 보고, 필터링하고, 정렬하고, 표시할 수 있습니다.

이 가이드에서는 코드 없는 솔루션부터 프로그래밍 방식 접근 방식에 이르기까지 JSON을 Excel로 변환하는 다섯 가지 실용적인 방법을 보여줍니다.

다루는 방법 개요:

JSON 구조 준비

JSON을 Excel로 변환하기 전에 JSON 데이터의 구조가 변환 프로세스에 어떤 영향을 미치는지 이해하는 것이 중요합니다. 많은 변환 도구는 특정 형식을 가정하며, 구조가 일치하지 않으면 예기치 않은 결과나 오류가 발생할 수 있습니다.

루트 배열 대 루트 객체

많은 JSON-to-Excel 도구는 데이터가 다음과 같은 객체의 루트 배열이기를 기대합니다.

[
  {"id":1,"name":"Alice"},
  {"id":2,"name":"Bob"}
]

이 구조는 Excel 테이블에 자연스럽게 매핑됩니다.

id name
1 Alice
2 Bob

각 객체는 행이 되고 키는 열 머리글이 됩니다.

그러나 많은 실제 API 및 데이터 세트는 배열을 루트 객체 내에 래핑합니다.

{
  "employees":[
    {"id":1,"name":"Alice"},
    {"id":2,"name":"Bob"}
  ]
}

이 경우 실제 테이블 형식 데이터 세트는 "employees" 속성 내에 저장됩니다.

일부 도구가 루트 객체에서 실패하는 이유

일부 변환기는 테이블 형식 데이터 세트를 포함하는 속성을 자동으로 결정할 수 없습니다. JSON 파일이 배열로 직접 시작될 것으로 예상합니다.

데이터가 루트 객체 내에 래핑되면 이러한 도구는 파일을 올바르게 구문 분석하지 못하거나 빈 결과를 생성할 수 있습니다.

따라서 변환을 수행하기 전에 관련 배열을 수동으로 추출해야 할 수 있습니다. 예를 들어, 배열이 온라인 변환기의 루트 요소가 되도록 JSON을 재구성하거나 코드에서 직접 액세스할 수 있습니다.

Python에서 배열에 액세스하기

예를 들어, 데이터 세트가 "employees" 아래에 저장된 경우 다음과 같이 로드하고 추출할 수 있습니다.

data = json.load(f)["employees"]

이 단계가 끝나면 data객체 목록이 되며, 이를 행과 열로 Excel에 쉽게 쓸 수 있습니다.

방법 1 — Excel 파워 쿼리 (코드 없음)

Microsoft Excel이 이미 설치되어 있는 경우 코드를 작성하지 않고도 JSON 데이터를 직접 가져올 수 있습니다. Excel의 파워 쿼리 기능을 사용하면 사용자가 JSON 파일을 로드하고 자동으로 테이블 형식으로 변환할 수 있습니다. 이 접근 방식은 스프레드시트 환경 내에서 JSON 데이터를 빠르게 보려는 분석가나 비즈니스 사용자에게 이상적입니다.

단계

  1. 컴퓨터에서 Microsoft Excel을 시작합니다.
  2. Excel 상단 메뉴에 있는 데이터 탭을 클릭합니다.
  3. 데이터 탭에서 데이터 가져오기로 이동한 다음 파일에서를 선택하고 드롭다운 메뉴에서 JSON에서를 선택합니다.
  4. JSON 파일에서 데이터 가져오기

  5. 메시지가 표시되면 JSON 파일을 찾아 선택한 다음 가져오기를 클릭합니다.
  6. 파워 쿼리 편집기가 시작됩니다.
  7. 파워 쿼리 편집기

  8. 파일이 레코드 목록으로 열리는 경우:

    • 테이블로를 클릭하여 목록을 테이블 형식으로 변환합니다.
    • 목록을 테이블로 변환

    • 그런 다음 열 머리글의 확장 (⇄) 아이콘을 클릭하여 열 이름을 표시합니다. 열에 여전히 "목록" 또는 "레코드"가 표시되면 확장 아이콘을 다시 클릭하여 더 평탄화합니다.
    • 목록 또는 레코드 확장

    • 테이블에 포함할 필드를 선택할 수 있는 대화 상자가 나타납니다. 필요한 필드를 선택하고 더 깔끔한 머리글을 위해 "접두사로 원래 열 이름 사용"을 선택 취소한 다음 확인을 클릭합니다.
    • 필요한 필드 선택

  9. 닫기 & 로드를 클릭하여 구조화된 데이터를 Excel 워크시트로 가져옵니다.
  10. 워크시트에 구조화된 데이터 로드

  11. 데이터가 나중에 사용할 수 있도록 보존되도록 Excel 파일을 .xlsx 형식으로 저장합니다.

이 방법을 사용하는 경우

프로그래밍보다 시각적 인터페이스를 선호하는 사용자 및 소규모 데이터 세트에 가장 적합합니다.

방법 2 — 온라인 JSON 변환기 (빠른 일회성)

온라인 JSON 변환기는 JSON 파일을 Excel 스프레드시트로 변환하는 가장 빠른 방법 중 하나를 제공합니다. 이러한 도구는 일반적으로 파일 업로드만 필요하며 다운로드 가능한 Excel 파일을 자동으로 생성합니다. jsontoexcel.net에서 제공하는 것과 같은 플랫폼은 소프트웨어를 설치하지 않고도 몇 초 만에 변환을 완료할 수 있습니다.

단계

  1. JSON-to-Excel 변환기 웹사이트를 엽니다.
  2. JSON 데이터를 텍스트 편집기에 직접 복사하여 붙여넣거나 컴퓨터에서 파일을 업로드합니다.
  3. Json 데이터를 붙여넣거나 온라인 변환기로 Json 로드

  4. Excel로 변환 버튼을 클릭하여 변환 프로세스를 시작합니다.
  5. 생성된 Excel 파일을 다운로드합니다.
  6. 생성된 Excel 파일 다운로드

중요 참고 사항

대부분의 온라인 변환기는 객체의 루트 배열을 예상합니다. 그렇지 않으면 자동으로 실패하거나 예기치 않은 결과가 발생할 수 있습니다. 이 형식은 Excel로 가장 안정적으로 변환됩니다.

이 방법을 사용하는 경우

빠른 일회성 변환 또는 샘플 데이터 세트 테스트에 가장 적합합니다.

방법 3 — pandas를 사용한 Python (자동화 친화적)

개발자와 데이터 엔지니어에게 Python은 JSON-to-Excel 변환을 자동화하는 강력한 방법을 제공합니다. 인기 있는 데이터 분석 라이브러리인 pandas는 JSON 파일을 쉽게 로드하고 구조화된 DataFrame으로 변환한 다음 결과를 Excel로 내보낼 수 있습니다. 이 방법은 변환을 스크립트, ETL 워크플로 또는 자동화된 보고 파이프라인에 통합해야 할 때 특히 유용합니다.

종속성 설치

pip install pandas openpyxl

JSON을 Excel로 변환

import pandas as pd
import json

with open("employees.json") as f:
    data = json.load(f)["employees"]

df = pd.json_normalize(data)
df.to_excel("output.xlsx", index=False)

Output:

pandas로 생성된 일반 Excel 시트

이 방법을 사용하는 경우

자동화된 데이터 처리, 분석 워크플로 및 대규모 데이터 세트에 이상적입니다.

방법 4 — Spire.XLS를 사용한 Python (서식이 지정된 Excel 보고서)

목표가 잘 서식 지정된 Excel 보고서를 생성하는 것이라면 Python은 Spire.XLS와 함께 작동하여 프로그래밍 방식으로 스프레드시트를 만들 수 있습니다. 간단한 데이터 내보내기 라이브러리와 달리 Spire.XLS는 Excel 서식에 대한 광범위한 제어를 제공하며, 글꼴, 색상, 정렬 및 열 크기 조정을 포함합니다. 따라서 이해 관계자와 공유할 준비가 된 전문적인 스프레드시트를 생성하는 데 적합합니다.

라이브러리 설치

pip install spire.xls

예제 코드

다음 스크립트는 JSON 직원 데이터를 읽고, 열 머리글을 동적으로 생성하고, 행을 Excel에 쓰고, 머리글 스타일 지정, 행 색상 교대 및 자동 맞춤 열과 같은 서식을 적용합니다.

import json
from spire.xls import *

# Load JSON data
with open('C:/Users/Administrator/Desktop/employees.json') as f:
    data = json.load(f)["employees"]

if not data:
    raise ValueError("JSON data is empty!")

# Create workbook and worksheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Extract headers dynamically
headers = list(data[0].keys())
num_cols = len(headers)

# Write headers
for col, header in enumerate(headers, start=1):
    sheet.Range[1, col].Value = header

# Write rows
for row_index, item in enumerate(data, start=2):
    for col_index, key in enumerate(headers, start=1):
        value = item.get(key, "")
        sheet.Range[row_index, col_index].Value = str(value) if value is not None else ""

# Header formatting
header_row = sheet.Range[1, 1, 1, num_cols]
header_row.RowHeight = 30
header_style = header_row.Style
header_style.Font.FontName = "Times New Roman"
header_style.Font.Size = 16
header_style.Font.Color = Color.get_White()
header_style.Color = Color.FromArgb(255, 128, 128, 128)
header_style.HorizontalAlignment = HorizontalAlignType.Center
header_style.VerticalAlignment = VerticalAlignType.Center

# Data formatting
locatedRange = sheet.AllocatedRange
for rowNum in range(2, locatedRange.RowCount + 1):
    data_row = sheet.Range[rowNum, 1, rowNum, num_cols]
    data_row.RowHeight = 20
    row_style = data_row.Style
    row_style.Font.FontName = "Times New Roman"
    row_style.Font.Size = 13
    row_style.HorizontalAlignment = HorizontalAlignType.Center
    row_style.VerticalAlignment = VerticalAlignType.Center
    row_style.Color = Color.get_White() if rowNum % 2 == 0 else Color.FromArgb(255, 245, 245, 245)

# Auto-fit columns
extra_width = 3
for col in range(1, num_cols + 1):
    sheet.AutoFitColumn(col)
    current_width = sheet.Columns[col - 1].ColumnWidth
    sheet.Columns[col - 1].ColumnWidth = current_width + extra_width

workbook.SaveToFile("JsonToExcel.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Output:

Spire.XLS로 생성된 잘 서식 지정된 Excel 시트

이 방법을 사용하는 경우

자동화된 보고서 생성, 정확한 Excel 서식이 필요한 응용 프로그램 및 Excel 파일이 최종 결과물인 워크플로에 가장 적합합니다.

관심 있을 만한 다른 글: Python에서 JSON을 Excel로/Excel에서 JSON으로 변환 – 예제가 포함된 전체 가이드

방법 5 — SheetJS를 사용한 Node.js (JavaScript 워크플로)

JavaScript 개발자는 SheetJS와 같은 라이브러리를 사용하여 JSON을 Excel로 변환할 수 있습니다. 이 라이브러리는 JSON 객체를 스프레드시트 워크시트로 변환하고 .xlsx 파일에 쓰는 유틸리티를 제공합니다. Node.js 환경에서 잘 작동하기 때문에 백엔드 서비스 및 데이터 처리 스크립트에서 일반적으로 사용됩니다.

설치

npm install xlsx

예제

const XLSX = require("xlsx");
const fs = require("fs");

const data = JSON.parse(fs.readFileSync("employees.json")).employees;

const worksheet = XLSX.utils.json_to_sheet(data);
const workbook = XLSX.utils.book_new();

XLSX.utils.book_append_sheet(workbook, worksheet, "Employees");
XLSX.writeFile(workbook, "output.xlsx");

Output:

SheetJS로 생성된 일반 Excel 시트

이 방법을 사용하는 경우

웹 응용 프로그램, Node.js 백엔드 및 JavaScript 기반 자동화 워크플로에 가장 적합합니다.

5가지 방법 빠른 비교

JSON을 Excel로 변환하는 각 방법은 다른 유형의 사용자 및 워크플로에 적합합니다. 일부 접근 방식은 단순성과 속도에 중점을 두는 반면, 다른 접근 방식은 고급 시나리오를 위한 자동화 및 서식 제어를 제공합니다. 아래 표는 가장 적합한 옵션을 선택하는 데 도움이 되도록 주요 차이점을 요약합니다.

방법 기술 수준 자동화 최적 대상 제한 사항
Excel (파워 쿼리) 초급 아니요 빠른 수동 변환 및 데이터 탐색 수동 단계 필요; 반복적인 워크플로에 제한적
온라인 변환기 초급 아니요 일회성 변환 및 빠른 테스트 파일 크기 제한; 잠재적인 개인 정보 보호 문제
pandas를 사용한 Python 중급 데이터 파이프라인, 분석 및 대규모 데이터 세트 고급 Excel 서식에 대한 제한된 제어
Spire.XLS를 사용한 Python 중급 전문적인 Excel 보고서 생성 추가 라이브러리 설정 필요
SheetJS를 사용한 Node.js 중급 JavaScript 응용 프로그램 및 백엔드 자동화 Node.js 환경 필요

JSON을 Excel로 변환하기 위한 모범 사례

JSON을 Excel로 변환하는 것은 간단해 보일 수 있지만, 실제 데이터 세트에는 종종 중첩된 구조, 일관성 없는 키 또는 대량의 데이터가 포함됩니다. 몇 가지 모범 사례를 따르면 안정적이고 읽기 쉬운 결과를 보장하는 데 도움이 될 수 있습니다.

  1. 중첩된 JSON 구조 평탄화
  2. 많은 JSON 파일에는 중첩된 객체나 배열이 포함되어 있습니다. JSON은 계층적 데이터를 지원하지만 Excel은 평평한 테이블 형식 구조에서 가장 잘 작동합니다.

    예를 들어, 다음과 같은 JSON:

    {
      "id": 1,
      "name": "Alice",
      "address": {
        "city": "San Francisco",
        "zip": "94105"
      }
    }
    

    다음과 같이 평탄화해야 할 수 있습니다.

    id name address.city address.zip
    1 Alice San Francisco 94105

    pandas와 같은 라이브러리는 json_normalize()와 같은 도구를 제공하여 중첩된 데이터를 자동으로 평탄화합니다. 더 복잡한 JSON으로 작업할 때 Excel로 내보내기 전에 구조를 전처리하면 종종 더 깔끔한 결과를 얻을 수 있습니다.

  3. 파일 크기 및 성능 고려

    대규모 JSON 데이터 세트에는 수천 또는 수백만 개의 레코드가 포함될 수 있으며, 이는 Excel로 직접 변환할 때 성능 문제를 일으킬 수 있습니다. 몇 가지 팁:

    • 대용량 파일에는 프로그래밍 방식 솔루션(Python 또는 Node.js)을 사용합니다.
    • 필요한 경우 데이터를 일괄 처리합니다.
    • 매우 큰 데이터 세트를 Excel에 직접 로드하지 마십시오.

    Excel 자체에는 제한(예: 시트당 약 1,048,576개 행)이 있으므로 매우 큰 데이터 세트는 여러 워크시트로 분할해야 할 수 있습니다.

  4. 복잡한 데이터에 여러 시트 사용
  5. 일부 API는 다음과 같이 여러 관련 배열이 있는 JSON을 반환합니다.

    {
      "customers": [...],
      "orders": [...],
      "products": [...]
    }
    

    모든 것을 하나의 워크시트에 강제로 넣는 대신 각 데이터 세트를 별도의 Excel 시트로 내보내는 것을 고려하십시오. 이렇게 하면 원본 데이터의 논리적 구조가 보존되고 분석이 더 쉬워집니다.

  6. 가독성 향상을 위한 서식 적용

    Excel 파일을 동료나 이해 관계자와 공유할 경우 서식을 지정하면 가독성을 크게 향상시킬 수 있습니다.

    유용한 서식 지정 방법은 다음과 같습니다.

    • 굵은 머리글 행
    • 조정된 열 너비
    • 교대 행 색상
    • 일관된 글꼴 및 정렬

    Spire.XLS와 같은 라이브러리를 사용하면 이러한 요소를 프로그래밍 방식으로 제어할 수 있으므로 프레젠테이션 준비가 된 보고서를 자동으로 생성할 수 있습니다.

결론

JSON은 구조화된 데이터를 저장하고 교환하는 데 널리 사용되지만, 비기술적인 사용자와 분석하거나 공유하기에 항상 이상적인 것은 아닙니다. JSON을 Excel로 변환하면 익숙한 스프레드시트 형식으로 데이터를 더 쉽게 읽고, 필터링하고, 구성할 수 있습니다.

간단한 일회성 변환의 경우 Excel이나 온라인 변환기와 같은 도구로 충분한 경우가 많습니다. 그러나 데이터 파이프라인이나 자동화된 보고서로 작업하는 개발자는 출력에 대한 더 큰 유연성과 제어를 제공하는 pandas, Spire.XLS 또는 SheetJS와 같은 프로그래밍 방식 솔루션의 이점을 누릴 수 있습니다.

자주 묻는 질문

Q1. 일부 온라인 변환기가 유효한 JSON을 거부하는 이유는 무엇입니까?

많은 온라인 변환기는 데이터 세트로 객체의 루트 배열을 예상합니다. JSON 파일이 중첩된 배열을 포함하는 루트 객체로 시작하는 경우 도구는 어떤 속성이 테이블을 나타내는지 알 수 없습니다. 파일을 업로드하기 전에 관련 배열을 추출하면 일반적으로 이 문제가 해결됩니다.

Q2. JSON 배열과 JSON 객체의 차이점은 무엇입니까?

JSON 배열은 대괄호 []로 묶인 순서 있는 값 목록이고, JSON 객체는 중괄호 {}로 묶인 키-값 쌍의 모음입니다.

Q3. 중첩된 JSON을 Excel로 어떻게 변환할 수 있습니까?

중첩된 JSON은 종종 Excel로 내보내기 전에 평탄화해야 합니다. pandas와 같은 도구는 중첩된 필드를 열로 자동 확장하는 json_normalize()와 같은 함수를 제공합니다. 또는 데이터를 쓰기 전에 중첩된 객체나 배열을 수동으로 추출할 수 있습니다.

Q4. Excel에서 JSON 파일을 직접 열 수 있습니까?

예. Excel에는 JSON 파일을 가져와서 테이블로 변환할 수 있는 파워 쿼리라는 기능이 포함되어 있습니다. 그러나 이 프로세스는 깔끔한 테이블 형식 데이터 세트를 얻기 위해 중첩된 구조를 수동으로 확장해야 할 수 있습니다.

함께 읽기

Convertire JSON in Excel: Guida Completa

JSON è uno dei formati più utilizzati per archiviare e scambiare dati strutturati. API, file di configurazione e molte applicazioni moderne utilizzano JSON per rappresentare i set di dati.

Tuttavia, JSON non è sempre comodo per analisi, reporting o condivisione con utenti non tecnici. In molti casi, convertire i dati JSON in un foglio di calcolo Excel rende più facile visualizzare, filtrare, ordinare e presentare le informazioni.

Questa guida mostra cinque metodi pratici per convertire JSON in Excel, che vanno da soluzioni senza codice ad approcci programmatici.

Panoramica dei metodi trattati:

Prepara la tua struttura JSON

Prima di convertire JSON in Excel, è importante capire come la struttura dei tuoi dati JSON influisce sul processo di conversione. Molti strumenti di conversione presuppongono un formato specifico e strutture non corrispondenti possono causare risultati imprevisti o errori.

Array Radice vs. Oggetto Radice

Molti strumenti da JSON a Excel si aspettano che i dati siano un array di oggetti radice, come questo:

[
  {"id":1,"name":"Alice"},
  {"id":2,"name":"Bob"}
]

Questa struttura si mappa naturalmente a una tabella di Excel:

id nome
1 Alice
2 Bob

Ogni oggetto diventa una riga e le chiavi diventano intestazioni di colonna.

Tuttavia, molte API e set di dati del mondo reale racchiudono l'array all'interno di un oggetto radice:

{
  "employees":[
    {"id":1,"name":"Alice"},
    {"id":2,"name":"Bob"}
  ]
}

In questo caso, il set di dati tabellare effettivo è archiviato all'interno della proprietà "employees".

Perché Alcuni Strumenti Falliscono con gli Oggetti Radice

Alcuni convertitori non possono determinare automaticamente quale proprietà contiene il set di dati tabellare. Si aspettano che il file JSON inizi direttamente con un array.

Quando i dati sono racchiusi in un oggetto radice, questi strumenti potrebbero non riuscire a analizzare correttamente il file o produrre risultati vuoti.

Pertanto, potrebbe essere necessario estrarre manualmente l'array pertinente prima di eseguire la conversione. Ad esempio, potresti ristrutturare il JSON in modo che l'array diventi l'elemento radice per un convertitore online, o accedervi direttamente nel codice.

Accesso all'Array in Python

Ad esempio, se il set di dati è archiviato sotto "employees", puoi caricarlo ed estrarlo in questo modo:

data = json.load(f)["employees"]

Dopo questo passaggio, data diventa una lista di oggetti, che può essere facilmente scritta in Excel come righe e colonne.

Metodo 1 — Excel Power Query (Senza Codice)

Se hai già installato Microsoft Excel, puoi importare i dati JSON direttamente senza scrivere alcun codice. La funzione Power Query di Excel consente agli utenti di caricare file JSON e convertirli automaticamente in un formato tabellare. Questo approccio è ideale per analisti o utenti aziendali che desiderano visualizzare rapidamente i dati JSON all'interno di un ambiente di foglio di calcolo.

Passaggi

  1. Avvia Microsoft Excel sul tuo computer.
  2. Fai clic sulla scheda Dati situata nel menu superiore di Excel.
  3. Nella scheda Dati, vai a Recupera dati, quindi seleziona Da file e scegli Da JSON dal menu a discesa.
  4. Ottieni Dati da File JSON

  5. Quando richiesto, individua e seleziona il tuo file JSON, quindi fai clic su Importa.
  6. Si avvierà l'Editor di Power Query.
  7. Editor di Power Query

  8. Se il file si apre come un elenco di record:

    • Fai clic su In tabella per convertire l'elenco in un formato di tabella.
    • Converti Elenco in Tabella

    • Quindi, fai clic sull'icona Espandi (⇄) nell'intestazione della colonna per rivelare i nomi delle colonne. Se le colonne mostrano ancora "Elenco" o "Record", fai di nuovo clic sull'icona di espansione per appiattire ulteriormente.
    • Espandi elenchi o record

    • Apparirà una finestra di dialogo che ti consentirà di selezionare quali campi desideri includere nella tabella. Scegli i campi necessari, deseleziona "Usa nome colonna originale come prefisso" per intestazioni più pulite, quindi fai clic su OK.
    • Scegli i campi necessari

  9. Fai clic su Chiudi e carica per importare i dati strutturati nel tuo foglio di lavoro Excel.
  10. Carica dati strutturati nel foglio di lavoro

  11. Salva il tuo file Excel in formato .xlsx, assicurandoti che i tuoi dati siano conservati per un uso futuro.

Quando usare questo metodo

Ideale per piccoli set di dati e utenti che preferiscono un'interfaccia visiva piuttosto che la programmazione.

Metodo 2 — Convertitore JSON Online (Veloce e Singolo)

I convertitori JSON online offrono uno dei modi più veloci per trasformare i file JSON in fogli di calcolo Excel. Questi strumenti richiedono in genere solo il caricamento di un file e generano automaticamente un file Excel scaricabile. Piattaforme come quelle offerte da jsontoexcel.net possono completare la conversione in pochi secondi senza installare alcun software.

Passaggi

  1. Apri un sito web di conversione da JSON a Excel.
  2. Copia e incolla i tuoi dati JSON direttamente nell'editor di testo o carica un file dal tuo computer.
  3. Incolla dati Json o carica Json nel convertitore online

  4. Fai clic sul pulsante Converti in Excel per avviare il processo di conversione.
  5. Scarica il file Excel generato.
  6. Scarica il file Excel generato

Nota Importante

La maggior parte dei convertitori online si aspetta un array di oggetti radice; in caso contrario, potrebbero fallire silenziosamente o produrre risultati imprevisti. Questo formato si converte in modo più affidabile in Excel.

Quando usare questo metodo

Ideale per conversioni rapide e una tantum o per testare set di dati di esempio.

Metodo 3 — Python con pandas (Adatto all'Automazione)

Per sviluppatori e ingegneri dei dati, Python offre un modo potente per automatizzare le conversioni da JSON a Excel. La popolare libreria di analisi dei dati pandas può caricare facilmente file JSON, trasformarli in un DataFrame strutturato ed esportare i risultati in Excel. Questo metodo è particolarmente utile quando la conversione deve essere integrata in script, flussi di lavoro ETL o pipeline di reporting automatizzate.

Installa Dipendenze

pip install pandas openpyxl

Converti JSON in Excel

import pandas as pd
import json

with open("employees.json") as f:
    data = json.load(f)["employees"]

df = pd.json_normalize(data)
df.to_excel("output.xlsx", index=False)

Output:

Foglio Excel semplice generato da pandas

Quando usare questo metodo

Ideale per l'elaborazione automatizzata dei dati, i flussi di lavoro di analisi e i grandi set di dati.

Metodo 4 — Python con Spire.XLS (Report Excel Formattati)

Se il tuo obiettivo è generare report Excel ben formattati, Python può funzionare con Spire.XLS per creare fogli di calcolo in modo programmatico. A differenza delle semplici librerie di esportazione dati, Spire.XLS offre un controllo esteso sulla formattazione di Excel, inclusi caratteri, colori, allineamento e dimensionamento delle colonne. Ciò lo rende adatto per produrre fogli di calcolo professionali pronti per essere condivisi con gli stakeholder.

Installa la Libreria

pip install spire.xls

Codice di Esempio

Lo script seguente legge i dati dei dipendenti JSON, genera dinamicamente le intestazioni delle colonne, scrive le righe in Excel e applica la formattazione come lo stile dell'intestazione, i colori alternati delle righe e le colonne adattate automaticamente.

import json
from spire.xls import *

# Load JSON data
with open('C:/Users/Administrator/Desktop/employees.json') as f:
    data = json.load(f)["employees"]

if not data:
    raise ValueError("JSON data is empty!")

# Create workbook and worksheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Extract headers dynamically
headers = list(data[0].keys())
num_cols = len(headers)

# Write headers
for col, header in enumerate(headers, start=1):
    sheet.Range[1, col].Value = header

# Write rows
for row_index, item in enumerate(data, start=2):
    for col_index, key in enumerate(headers, start=1):
        value = item.get(key, "")
        sheet.Range[row_index, col_index].Value = str(value) if value is not None else ""

# Header formatting
header_row = sheet.Range[1, 1, 1, num_cols]
header_row.RowHeight = 30
header_style = header_row.Style
header_style.Font.FontName = "Times New Roman"
header_style.Font.Size = 16
header_style.Font.Color = Color.get_White()
header_style.Color = Color.FromArgb(255, 128, 128, 128)
header_style.HorizontalAlignment = HorizontalAlignType.Center
header_style.VerticalAlignment = VerticalAlignType.Center

# Data formatting
locatedRange = sheet.AllocatedRange
for rowNum in range(2, locatedRange.RowCount + 1):
    data_row = sheet.Range[rowNum, 1, rowNum, num_cols]
    data_row.RowHeight = 20
    row_style = data_row.Style
    row_style.Font.FontName = "Times New Roman"
    row_style.Font.Size = 13
    row_style.HorizontalAlignment = HorizontalAlignType.Center
    row_style.VerticalAlignment = VerticalAlignType.Center
    row_style.Color = Color.get_White() if rowNum % 2 == 0 else Color.FromArgb(255, 245, 245, 245)

# Auto-fit columns
extra_width = 3
for col in range(1, num_cols + 1):
    sheet.AutoFitColumn(col)
    current_width = sheet.Columns[col - 1].ColumnWidth
    sheet.Columns[col - 1].ColumnWidth = current_width + extra_width

workbook.SaveToFile("JsonToExcel.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Output:

Foglio Excel ben formattato generato da Spire.XLS

Quando usare questo metodo

Ideale per la generazione automatizzata di report, applicazioni che richiedono una formattazione precisa di Excel e flussi di lavoro in cui i file Excel sono il prodotto finale.

Potrebbe Piacerti Anche: Convertire JSON da/a Excel in Python – Guida Completa con Esempi

Metodo 5 — Node.js con SheetJS (Flusso di Lavoro JavaScript)

Gli sviluppatori JavaScript possono convertire JSON in Excel utilizzando librerie come SheetJS. Questa libreria fornisce utilità per trasformare oggetti JSON in fogli di lavoro per fogli di calcolo e scriverli in file .xlsx. Poiché funziona bene negli ambienti Node.js, è comunemente utilizzata nei servizi di backend e negli script di elaborazione dati.

Installa

npm install xlsx

Esempio

const XLSX = require("xlsx");
const fs = require("fs");

const data = JSON.parse(fs.readFileSync("employees.json")).employees;

const worksheet = XLSX.utils.json_to_sheet(data);
const workbook = XLSX.utils.book_new();

XLSX.utils.book_append_sheet(workbook, worksheet, "Employees");
XLSX.writeFile(workbook, "output.xlsx");

Output:

Foglio Excel semplice generato da SheetJS

Quando usare questo metodo

Ideale per applicazioni web, backend Node.js e flussi di lavoro di automazione basati su JavaScript.

Confronto Rapido dei 5 Metodi

Ogni metodo per convertire JSON in Excel serve un diverso tipo di utente e flusso di lavoro. Alcuni approcci si concentrano su semplicità e velocità, while others provide automazione e controllo della formattazione per scenari più avanzati. La tabella seguente riassume le principali differenze per aiutarti a scegliere l'opzione più adatta.

Metodo Livello di Abilità Automazione Ideale Per Limitazioni
Excel (Power Query) Principiante No Conversione manuale rapida ed esplorazione dei dati Richiede passaggi manuali; limitato per flussi di lavoro ripetuti
Convertitore Online Principiante No Conversioni una tantum e test rapidi Limiti di dimensione del file; potenziali problemi di privacy
Python con pandas Intermedio Pipeline di dati, analisi e grandi set di dati Controllo limitato sulla formattazione avanzata di Excel
Python con Spire.XLS Intermedio Generazione di report Excel professionali Richiede la configurazione di una libreria aggiuntiva
Node.js con SheetJS Intermedio Applicazioni JavaScript e automazione di backend Richiede un ambiente Node.js

Migliori Pratiche per Convertire JSON in Excel

La conversione da JSON a Excel può sembrare semplice, ma i set di dati del mondo reale contengono spesso strutture annidate, chiavi incoerenti o grandi volumi di dati. Seguire alcune migliori pratiche può aiutare a garantire risultati affidabili e leggibili.

  1. Appiattire le Strutture JSON Annidate
  2. Molti file JSON contengono oggetti o array annidati. Mentre JSON supporta dati gerarchici, Excel funziona meglio con strutture piatte e tabellari.

    Ad esempio, JSON come questo:

    {
      "id": 1,
      "name": "Alice",
      "address": {
        "city": "San Francisco",
        "zip": "94105"
      }
    }
    

    potrebbe essere necessario appiattirlo in:

    id nome address.city address.zip
    1 Alice San Francisco 94105

    Librerie come pandas forniscono strumenti come json_normalize() per appiattire automaticamente i dati annidati. Quando si lavora con JSON più complessi, la pre-elaborazione della struttura prima dell'esportazione in Excel produce spesso risultati più puliti.

  3. Considera la Dimensione del File e le Prestazioni

    Grandi set di dati JSON possono contenere migliaia o milioni di record, il che può causare problemi di prestazioni durante la conversione diretta in Excel. Alcuni suggerimenti:

    • Usa soluzioni programmatiche (Python o Node.js) per file di grandi dimensioni.
    • Elabora i dati in batch se necessario.
    • Evita di caricare set di dati estremamente grandi direttamente in Excel.

    Excel stesso ha dei limiti (ad esempio, circa 1.048.576 righe per foglio), quindi set di dati molto grandi potrebbero dover essere suddivisi su più fogli di lavoro.

  4. Usa Fogli Multipli per Dati Complessi
  5. Alcune API restituiscono JSON con array correlati multipli, come:

    {
      "customers": [...],
      "orders": [...],
      "products": [...]
    }
    

    Invece di forzare tutto in un unico foglio di lavoro, considera di esportare ogni set di dati in fogli Excel separati. Ciò preserva la struttura logica dei dati originali e facilita l'analisi.

  6. Applica la Formattazione per una Migliore Leggibilità

    Se il file Excel verrà condiviso con colleghi o stakeholder, la formattazione può migliorare significativamente la leggibilità.

    Le pratiche di formattazione utili includono:

    • Righe di intestazione in grassetto
    • Larghezze delle colonne regolate
    • Colori delle righe alternati
    • Caratteri e allineamento coerenti

    Librerie come Spire.XLS consentono il controllo programmatico su questi elementi, rendendo possibile la generazione di report pronti per la presentazione automaticamente.

Conclusione

JSON è ampiamente utilizzato per archiviare e scambiare dati strutturati, ma non è sempre ideale per l'analisi o la condivisione con utenti non tecnici. La conversione di JSON in Excel rende i dati più facili da leggere, filtrare e organizzare in un formato di foglio di calcolo familiare.

Per conversioni semplici e una tantum, strumenti come Excel o convertitori online sono spesso sufficienti. Tuttavia, gli sviluppatori che lavorano con pipeline di dati o report automatizzati trarranno vantaggio da soluzioni programmatiche come pandas, Spire.XLS, o SheetJS, che offrono maggiore flessibilità e controllo sull'output.

Domande Frequenti

D1. Perché alcuni convertitori online rifiutano JSON validi?

Molti convertitori online si aspettano un array di oggetti radice come set di dati. Se il file JSON inizia con un oggetto radice contenente array annidati, lo strumento potrebbe non sapere quale proprietà rappresenta la tabella. L'estrazione dell'array pertinente prima di caricare il file di solito risolve questo problema.

D2. Qual è la differenza tra un array JSON e un oggetto JSON?

Un array JSON è un elenco ordinato di valori racchiusi tra parentesi quadre [], mentre un oggetto JSON è una raccolta di coppie chiave-valore racchiuse tra parentesi graffe {}.

D3. Come posso convertire JSON annidato in Excel?

Il JSON annidato richiede spesso l'appiattimento prima dell'esportazione in Excel. Strumenti come pandas forniscono funzioni come json_normalize() che espandono automaticamente i campi annidati in colonne. In alternativa, è possibile estrarre manualmente oggetti o array annidati prima di scrivere i dati.

D4. Excel può aprire direttamente i file JSON?

Sì. Excel include una funzione chiamata Power Query, che può importare file JSON e convertirli in tabelle. Tuttavia, il processo potrebbe richiedere l'espansione manuale delle strutture annidate per ottenere un set di dati tabellare pulito.

Leggi Anche

Convertir JSON en Excel : Guide complet

Le JSON est l'un des formats les plus utilisés pour stocker et échanger des données structurées. Les API, les fichiers de configuration et de nombreuses applications modernes utilisent le JSON pour représenter des ensembles de données.

Cependant, le JSON n'est pas toujours pratique pour l'analyse, le reporting ou le partage avec des utilisateurs non techniques. Dans de nombreux cas, la conversion des données JSON en une feuille de calcul Excel facilite la visualisation, le filtrage, le tri et la présentation des informations.

Ce guide présente cinq méthodes pratiques pour convertir du JSON en Excel, allant des solutions sans code aux approches programmatiques.

Aperçu des méthodes couvertes :

Préparez votre structure JSON

Avant de convertir du JSON en Excel, il est important de comprendre comment la structure de vos données JSON affecte le processus de conversion. De nombreux outils de conversion supposent un format spécifique, et des structures incompatibles peuvent entraîner des résultats inattendus ou des erreurs.

Tableau racine vs. Objet racine

De nombreux outils de conversion JSON vers Excel s'attendent à ce que les données soient un tableau racine d'objets, comme ceci :

[
  {"id":1,"name":"Alice"},
  {"id":2,"name":"Bob"}
]

Cette structure correspond naturellement à un tableau Excel :

id name
1 Alice
2 Bob

Chaque objet devient une ligne, et les clés deviennent des en-têtes de colonne.

Cependant, de nombreuses API et ensembles de données du monde réel encapsulent le tableau à l'intérieur d'un objet racine :

{
  "employees":[
    {"id":1,"name":"Alice"},
    {"id":2,"name":"Bob"}
  ]
}

Dans ce cas, l'ensemble de données tabulaires réel est stocké à l'intérieur de la propriété "employees".

Pourquoi certains outils échouent avec les objets racines

Certains convertisseurs ne peuvent pas déterminer automatiquement quelle propriété contient l'ensemble de données tabulaires. Ils s'attendent à ce que le fichier JSON commence directement par un tableau.

Lorsque les données sont encapsulées dans un objet racine, ces outils peuvent ne pas réussir à analyser correctement le fichier ou produire des résultats vides.

Par conséquent, vous devrez peut-être extraire manuellement le tableau pertinent avant d'effectuer la conversion. Par exemple, vous pourriez restructurer le JSON pour que le tableau devienne l'élément racine pour un convertisseur en ligne, ou y accéder directement dans le code.

Accéder au tableau en Python

Par exemple, si l'ensemble de données est stocké sous "employees", vous pouvez le charger et l'extraire comme ceci :

data = json.load(f)["employees"]

Après cette étape, data devient une liste d'objets, qui peut être facilement écrite dans Excel sous forme de lignes et de colonnes.

Méthode 1 — Excel Power Query (sans code)

Si vous avez déjà installé Microsoft Excel, vous pouvez importer des données JSON directement sans écrire de code. La fonctionnalité Power Query d'Excel permet aux utilisateurs de charger des fichiers JSON et de les convertir automatiquement en format tabulaire. Cette approche est idéale pour les analystes ou les utilisateurs professionnels qui souhaitent visualiser rapidement des données JSON dans un environnement de feuille de calcul.

Étapes

  1. Lancez Microsoft Excel sur votre ordinateur.
  2. Cliquez sur l'onglet Données situé dans le menu supérieur d'Excel.
  3. Dans l'onglet Données, naviguez vers Obtenir des données, puis sélectionnez À partir d'un fichier, et choisissez À partir de JSON dans le menu déroulant.
  4. Obtenir des données à partir d'un fichier JSON

  5. Lorsque vous y êtes invité, localisez et sélectionnez votre fichier JSON, puis cliquez sur Importer.
  6. L'Éditeur Power Query se lancera.
  7. Éditeur Power Query

  8. Si le fichier s'ouvre comme une liste d'enregistrements :

    • Cliquez sur Vers la table pour convertir la liste en format de tableau.
    • Convertir la liste en table

    • Ensuite, cliquez sur l'icône Développer (⇄) dans l'en-tête de colonne pour afficher les noms de colonnes. Si les colonnes affichent toujours "List" ou "Record", cliquez à nouveau sur l'icône de développement pour aplatir davantage.
    • Développer les listes ou les enregistrements

    • Une boîte de dialogue apparaîtra, vous permettant de sélectionner les champs que vous souhaitez inclure dans le tableau. Choisissez les champs nécessaires, décochez "Utiliser le nom de la colonne d'origine comme préfixe" pour des en-têtes plus propres, puis cliquez sur OK.
    • Choisissez les champs nécessaires

  9. Cliquez sur Fermer et charger pour importer les données structurées dans votre feuille de calcul Excel.
  10. Charger les données structurées dans la feuille de calcul

  11. Enregistrez votre fichier Excel au format .xlsx, en vous assurant que vos données sont conservées pour une utilisation future.

Quand utiliser cette méthode

Idéal pour les petits ensembles de données et les utilisateurs qui préfèrent une interface visuelle plutôt que la programmation.

Méthode 2 — Convertisseur JSON en ligne (pour une conversion rapide et unique)

Les convertisseurs JSON en ligne offrent l'un des moyens les plus rapides de transformer des fichiers JSON en feuilles de calcul Excel. Ces outils ne nécessitent généralement qu'un téléchargement de fichier et génèrent automatiquement un fichier Excel téléchargeable. Des plateformes comme celles proposées par jsontoexcel.net peuvent effectuer la conversion en quelques secondes sans installer de logiciel.

Étapes

  1. Ouvrez un site web de convertisseur JSON vers Excel.
  2. Copiez et collez vos données JSON directement dans l'éditeur de texte, ou téléchargez un fichier depuis votre ordinateur.
  3. Coller les données Json ou charger le Json dans le convertisseur en ligne

  4. Cliquez sur le bouton Convertir en Excel pour lancer le processus de conversion.
  5. Téléchargez le fichier Excel généré.
  6. Téléchargez le fichier Excel généré

Note importante

La plupart des convertisseurs en ligne s'attendent à un tableau racine d'objets ; sinon, ils peuvent échouer silencieusement ou produire des résultats inattendus. Ce format se convertit de la manière la plus fiable en Excel.

Quand utiliser cette méthode

Idéal pour les conversions rapides et uniques ou pour tester des ensembles de données d'échantillons.

Méthode 3 — Python avec pandas (adapté à l'automatisation)

Pour les développeurs et les ingénieurs de données, Python offre un moyen puissant d'automatiser les conversions de JSON en Excel. La populaire bibliothèque d'analyse de données pandas peut facilement charger des fichiers JSON, les transformer en un DataFrame structuré et exporter les résultats vers Excel. Cette méthode est particulièrement utile lorsque la conversion doit être intégrée dans des scripts, des flux de travail ETL ou des pipelines de reporting automatisés.

Installer les dépendances

pip install pandas openpyxl

Convertir JSON en Excel

import pandas as pd
import json

with open("employees.json") as f:
    data = json.load(f)["employees"]

df = pd.json_normalize(data)
df.to_excel("output.xlsx", index=False)

Output:

Feuille Excel simple générée par pandas

Quand utiliser cette méthode

Idéal pour le traitement automatisé des données, les flux de travail d'analyse et les grands ensembles de données.

Méthode 4 — Python avec Spire.XLS (rapports Excel formatés)

Si votre objectif est de générer des rapports Excel bien formatés, Python peut fonctionner avec Spire.XLS pour créer des feuilles de calcul par programmation. Contrairement aux bibliothèques d'exportation de données simples, Spire.XLS offre un contrôle étendu sur le formatage Excel, y compris les polices, les couleurs, l'alignement et le dimensionnement des colonnes. Cela le rend approprié pour produire des feuilles de calcul professionnelles prêtes à être partagées avec les parties prenantes.

Installer la bibliothèque

pip install spire.xls

Exemple de code

Le script suivant lit les données des employés au format JSON, génère dynamiquement les en-têtes de colonne, écrit les lignes dans Excel et applique une mise en forme telle que le style des en-têtes, l'alternance des couleurs de lignes et l'ajustement automatique des colonnes.

import json
from spire.xls import *

# Load JSON data
with open('C:/Users/Administrator/Desktop/employees.json') as f:
    data = json.load(f)["employees"]

if not data:
    raise ValueError("JSON data is empty!")

# Create workbook and worksheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Extract headers dynamically
headers = list(data[0].keys())
num_cols = len(headers)

# Write headers
for col, header in enumerate(headers, start=1):
    sheet.Range[1, col].Value = header

# Write rows
for row_index, item in enumerate(data, start=2):
    for col_index, key in enumerate(headers, start=1):
        value = item.get(key, "")
        sheet.Range[row_index, col_index].Value = str(value) if value is not None else ""

# Header formatting
header_row = sheet.Range[1, 1, 1, num_cols]
header_row.RowHeight = 30
header_style = header_row.Style
header_style.Font.FontName = "Times New Roman"
header_style.Font.Size = 16
header_style.Font.Color = Color.get_White()
header_style.Color = Color.FromArgb(255, 128, 128, 128)
header_style.HorizontalAlignment = HorizontalAlignType.Center
header_style.VerticalAlignment = VerticalAlignType.Center

# Data formatting
locatedRange = sheet.AllocatedRange
for rowNum in range(2, locatedRange.RowCount + 1):
    data_row = sheet.Range[rowNum, 1, rowNum, num_cols]
    data_row.RowHeight = 20
    row_style = data_row.Style
    row_style.Font.FontName = "Times New Roman"
    row_style.Font.Size = 13
    row_style.HorizontalAlignment = HorizontalAlignType.Center
    row_style.VerticalAlignment = VerticalAlignType.Center
    row_style.Color = Color.get_White() if rowNum % 2 == 0 else Color.FromArgb(255, 245, 245, 245)

# Auto-fit columns
extra_width = 3
for col in range(1, num_cols + 1):
    sheet.AutoFitColumn(col)
    current_width = sheet.Columns[col - 1].ColumnWidth
    sheet.Columns[col - 1].ColumnWidth = current_width + extra_width

workbook.SaveToFile("JsonToExcel.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Output:

Feuille Excel bien formatée générée par Spire.XLS

Quand utiliser cette méthode

Idéal pour la génération automatisée de rapports, les applications nécessitant un formatage Excel précis et les flux de travail où les fichiers Excel sont le livrable final.

Vous pourriez aussi aimer : Convertir JSON vers/depuis Excel en Python – Guide complet avec exemples

Méthode 5 — Node.js avec SheetJS (flux de travail JavaScript)

Les développeurs JavaScript peuvent convertir du JSON en Excel en utilisant des bibliothèques telles que SheetJS. Cette bibliothèque fournit des utilitaires pour transformer des objets JSON en feuilles de calcul et les écrire dans des fichiers .xlsx. Parce qu'elle fonctionne bien dans les environnements Node.js, elle est couramment utilisée dans les services backend et les scripts de traitement de données.

Installer

npm install xlsx

Exemple

const XLSX = require("xlsx");
const fs = require("fs");

const data = JSON.parse(fs.readFileSync("employees.json")).employees;

const worksheet = XLSX.utils.json_to_sheet(data);
const workbook = XLSX.utils.book_new();

XLSX.utils.book_append_sheet(workbook, worksheet, "Employees");
XLSX.writeFile(workbook, "output.xlsx");

Output:

Feuille Excel simple générée par SheetJS

Quand utiliser cette méthode

Idéal pour les applications web, les backends Node.js et les flux de travail d'automatisation basés sur JavaScript.

Comparaison rapide des 5 méthodes

Chaque méthode de conversion de JSON en Excel s'adresse à un type d'utilisateur et à un flux de travail différents. Certaines approches se concentrent sur la simplicité et la rapidité, tandis que d'autres offrent un contrôle de l'automatisation et du formatage pour des scénarios plus avancés. Le tableau ci-dessous résume les principales différences pour vous aider à choisir l'option la plus appropriée.

Méthode Niveau de compétence Automatisation Idéal pour Limites
Excel (Power Query) Débutant Non Conversion manuelle rapide et exploration de données Nécessite des étapes manuelles ; limité pour les flux de travail répétés
Convertisseur en ligne Débutant Non Conversions uniques et tests rapides Limites de taille de fichier ; préoccupations potentielles en matière de confidentialité
Python avec pandas Intermédiaire Oui Pipelines de données, analyses et grands ensembles de données Contrôle limité sur le formatage Excel avancé
Python avec Spire.XLS Intermédiaire Oui Génération de rapports Excel professionnels Nécessite une configuration de bibliothèque supplémentaire
Node.js avec SheetJS Intermédiaire Oui Applications JavaScript et automatisation du backend Nécessite un environnement Node.js

Meilleures pratiques pour la conversion de JSON en Excel

La conversion de JSON en Excel peut sembler simple, mais les ensembles de données du monde réel contiennent souvent des structures imbriquées, des clés incohérentes ou de grands volumes de données. Suivre quelques meilleures pratiques peut aider à garantir des résultats fiables et lisibles.

  1. Aplatir les structures JSON imbriquées
  2. De nombreux fichiers JSON contiennent des objets ou des tableaux imbriqués. Alors que le JSON prend en charge les données hiérarchiques, Excel fonctionne mieux avec des structures plates et tabulaires.

    Par exemple, un JSON comme celui-ci :

    {
      "id": 1,
      "name": "Alice",
      "address": {
        "city": "San Francisco",
        "zip": "94105"
      }
    }
    

    peut avoir besoin d'être aplati en :

    id name address.city address.zip
    1 Alice San Francisco 94105

    Des bibliothèques telles que pandas fournissent des outils comme json_normalize() pour aplatir automatiquement les données imbriquées. Lorsque vous travaillez avec un JSON plus complexe, le prétraitement de la structure avant l'exportation vers Excel produit souvent des résultats plus propres.

  3. Tenir compte de la taille du fichier et des performances

    Les grands ensembles de données JSON peuvent contenir des milliers ou des millions d'enregistrements, ce qui peut entraîner des problèmes de performances lors de la conversion directe vers Excel. Quelques conseils :

    • Utilisez des solutions programmatiques (Python ou Node.js) pour les fichiers volumineux.
    • Traitez les données par lots si nécessaire.
    • Évitez de charger des ensembles de données extrêmement volumineux directement dans Excel.

    Excel lui-même a des limites (par exemple, environ 1 048 576 lignes par feuille), donc les très grands ensembles de données peuvent devoir être répartis sur plusieurs feuilles de calcul.

  4. Utiliser plusieurs feuilles pour les données complexes
  5. Certaines API renvoient du JSON avec plusieurs tableaux liés, tels que :

    {
      "customers": [...],
      "orders": [...],
      "products": [...]
    }
    

    Au lieu de tout forcer dans une seule feuille de calcul, envisagez d'exporter chaque ensemble de données dans des feuilles Excel séparées. Cela préserve la structure logique des données d'origine et facilite l'analyse.

  6. Appliquer une mise en forme pour une meilleure lisibilité

    Si le fichier Excel doit être partagé avec des collègues ou des parties prenantes, la mise en forme peut améliorer considérablement la lisibilité.

    Les pratiques de formatage utiles incluent :

    • Lignes d'en-tête en gras
    • Largeurs de colonne ajustées
    • Couleurs de lignes alternées
    • Polices et alignement cohérents

    Des bibliothèques comme Spire.XLS permettent un contrôle programmatique sur ces éléments, rendant possible la génération de rapports prêts à être présentés automatiquement.

Conclusion

Le JSON est largement utilisé pour stocker et échanger des données structurées, mais il n'est pas toujours idéal pour l'analyse ou le partage avec des utilisateurs non techniques. La conversion de JSON en Excel rend les données plus faciles à lire, à filtrer et à organiser dans un format de feuille de calcul familier.

Pour les conversions simples et uniques, des outils comme Excel ou les convertisseurs en ligne sont souvent suffisants. Cependant, les développeurs travaillant avec des pipelines de données ou des rapports automatisés bénéficieront de solutions programmatiques telles que pandas, Spire.XLS ou SheetJS, qui offrent une plus grande flexibilité et un meilleur contrôle sur le résultat.

FAQ

Q1. Pourquoi certains convertisseurs en ligne rejettent-ils un JSON valide ?

De nombreux convertisseurs en ligne s'attendent à un tableau racine d'objets comme ensemble de données. Si le fichier JSON commence par un objet racine contenant des tableaux imbriqués, l'outil peut ne pas savoir quelle propriété représente le tableau. L'extraction du tableau pertinent avant de télécharger le fichier résout généralement ce problème.

Q2. Quelle est la différence entre un tableau JSON et un objet JSON ?

Un tableau JSON est une liste ordonnée de valeurs entre crochets [], tandis qu'un objet JSON est une collection de paires clé-valeur entre accolades {}.

Q3. Comment puis-je convertir un JSON imbriqué en Excel ?

Le JSON imbriqué nécessite souvent un aplatissement avant d'être exporté vers Excel. Des outils comme pandas fournissent des fonctions telles que json_normalize() qui développent automatiquement les champs imbriqués en colonnes. Alternativement, vous pouvez extraire manuellement des objets ou des tableaux imbriqués avant d'écrire les données.

Q4. Excel peut-il ouvrir directement les fichiers JSON ?

Oui. Excel inclut une fonctionnalité appelée Power Query, qui peut importer des fichiers JSON et les convertir en tableaux. Cependant, le processus peut nécessiter de développer manuellement les structures imbriquées pour obtenir un ensemble de données tabulaires propre.

À lire également

Convertir JSON a Excel: Guía Completa

JSON es uno de los formatos más utilizados para almacenar e intercambiar datos estructurados. Las API, los archivos de configuración y muchas aplicaciones modernas utilizan JSON para representar conjuntos de datos.

Sin embargo, JSON no siempre es conveniente para el análisis, la generación de informes o el uso compartido con usuarios no técnicos. En muchos casos, convertir los datos JSON en una hoja de cálculo de Excel facilita la visualización, el filtrado, la clasificación y la presentación de la información.

Esta guía muestra cinco métodos prácticos para convertir JSON a Excel, que van desde soluciones sin código hasta enfoques programáticos.

Resumen de los métodos cubiertos:

Prepara tu Estructura JSON

Antes de convertir JSON a Excel, es importante comprender cómo la estructura de tus datos JSON afecta el proceso de conversión. Muchas herramientas de conversión asumen un formato específico, y las estructuras no coincidentes pueden causar resultados inesperados o errores.

Array Raíz vs. Objeto Raíz

Muchas herramientas de JSON a Excel esperan que los datos sean un array raíz de objetos, como este:

[
  {"id":1,"name":"Alice"},
  {"id":2,"name":"Bob"}
]

Esta estructura se asigna de forma natural a una tabla de Excel:

id nombre
1 Alice
2 Bob

Cada objeto se convierte en una fila y las claves se convierten en encabezados de columna.

Sin embargo, muchas API y conjuntos de datos del mundo real envuelven el array dentro de un objeto raíz:

{
  "employees":[
    {"id":1,"name":"Alice"},
    {"id":2,"name":"Bob"}
  ]
}

En este caso, el conjunto de datos tabular real se almacena dentro de la propiedad "employees".

Por Qué Algunas Herramientas Fallan con los Objetos Raíz

Algunos convertidores no pueden determinar automáticamente qué propiedad contiene el conjunto de datos tabular. Esperan que el archivo JSON comience directamente con un array.

Cuando los datos están envueltos dentro de un objeto raíz, estas herramientas pueden fallar al analizar el archivo correctamente o producir resultados vacíos.

Por lo tanto, es posible que debas extraer el array relevante manualmente antes de realizar la conversión. Por ejemplo, podrías reestructurar el JSON para que el array se convierta en el elemento raíz para un convertidor en línea, o acceder a él directamente en el código.

Accediendo al Array en Python

Por ejemplo, si el conjunto de datos se almacena en "employees", puedes cargarlo y extraerlo de esta manera:

data = json.load(f)["employees"]

Después de este paso, data se convierte en una lista de objetos, que se puede escribir fácilmente en Excel como filas y columnas.

Método 1 — Excel Power Query (Sin Código)

Si ya tienes Microsoft Excel instalado, puedes importar datos JSON directamente sin escribir ningún código. La función Power Query de Excel permite a los usuarios cargar archivos JSON y convertirlos automáticamente en un formato tabular. Este enfoque es ideal para analistas o usuarios de negocios que desean ver rápidamente los datos JSON dentro de un entorno de hoja de cálculo.

Pasos

  1. Inicia Microsoft Excel en tu computadora.
  2. Haz clic en la pestaña Datos ubicada en el menú superior de Excel.
  3. En la pestaña Datos, navega a Obtener Datos, luego selecciona Desde Archivo, y elige Desde JSON en el menú desplegable.
  4. Obtener Datos desde Archivo JSON

  5. Cuando se te solicite, busca y selecciona tu archivo JSON, luego haz clic en Importar.
  6. Se iniciará el Editor de Power Query.
  7. Editor de Power Query

  8. Si el archivo se abre como una lista de registros:

    • Haz clic en A la tabla para convertir la lista en un formato de tabla.
    • Convertir Lista en Tabla

    • Luego, haz clic en el icono Expandir (⇄) en el encabezado de la columna para revelar los nombres de las columnas. Si las columnas aún muestran "Lista" o "Registro," haz clic en el icono de expandir nuevamente para aplanar aún más.
    • Expandir listas o registros

    • Aparecerá un cuadro de diálogo que te permitirá seleccionar qué campos deseas incluir en la tabla. Elige los campos necesarios, desmarca "Usar el nombre de columna original como prefijo" para obtener encabezados más limpios, y luego haz clic en Aceptar.
    • Elige los campos necesarios

  9. Haz clic en Cerrar y Cargar para importar los datos estructurados a tu hoja de cálculo de Excel.
  10. Cargar datos estructurados en la hoja de cálculo

  11. Guarda tu archivo de Excel en formato .xlsx, asegurando que tus datos se conserven para uso futuro.

Cuándo usar este método

Ideal para conjuntos de datos pequeños y usuarios que prefieren una interfaz visual en lugar de la programación.

Método 2 — Convertidor JSON en Línea (Rápido y Único)

Los convertidores de JSON en línea ofrecen una de las formas más rápidas de convertir archivos JSON en hojas de cálculo de Excel. Estas herramientas generalmente solo requieren la carga de un archivo y generan automáticamente un archivo de Excel descargable. Plataformas como las ofrecidas por jsontoexcel.net pueden completar la conversión en segundos sin instalar ningún software.

Pasos

  1. Abre un sitio web de conversión de JSON a Excel.
  2. Copia y pega tus datos JSON directamente en el editor de texto, o sube un archivo desde tu computadora.
  3. Pega los datos Json o carga el Json en el convertidor en línea

  4. Haz clic en el botón Convertir a Excel para iniciar el proceso de conversión.
  5. Descarga el archivo de Excel generado.
  6. Descarga el archivo de Excel generado

Nota Importante

La mayoría de los convertidores en línea esperan un array raíz de objetos; de lo contrario, pueden fallar silenciosamente o producir resultados inesperados. Este formato se convierte de manera más confiable a Excel.

Cuándo usar este método

Ideal para conversiones rápidas y únicas o para probar conjuntos de datos de muestra.

Método 3 — Python con pandas (Amigable para la Automatización)

Para desarrolladores e ingenieros de datos, Python proporciona una forma poderosa de automatizar las conversiones de JSON a Excel. La popular biblioteca de análisis de datos pandas puede cargar fácilmente archivos JSON, transformarlos en un DataFrame estructurado y exportar los resultados a Excel. Este método es particularmente útil cuando la conversión necesita integrarse en scripts, flujos de trabajo de ETL o canalizaciones de informes automatizados.

Instalar Dependencias

pip install pandas openpyxl

Convertir JSON a Excel

import pandas as pd
import json

with open("employees.json") as f:
    data = json.load(f)["employees"]

df = pd.json_normalize(data)
df.to_excel("output.xlsx", index=False)

Salida:

Hoja de Excel simple generada por pandas

Cuándo usar este método

Ideal para el procesamiento automatizado de datos, flujos de trabajo de análisis y grandes conjuntos de datos.

Método 4 — Python con Spire.XLS (Informes de Excel con Formato)

Si tu objetivo es generar informes de Excel bien formateados, Python puede trabajar con Spire.XLS para crear hojas de cálculo programáticamente. A diferencia de las bibliotecas de exportación de datos simples, Spire.XLS proporciona un control extenso sobre el formato de Excel, incluyendo fuentes, colores, alineación y tamaño de las columnas. Esto lo hace adecuado para producir hojas de cálculo profesionales que están listas para compartir con las partes interesadas.

Instalar la Biblioteca

pip install spire.xls

Código de Ejemplo

El siguiente script lee datos de empleados en formato JSON, genera dinámicamente encabezados de columna, escribe filas en Excel y aplica formato como estilo de encabezado, colores de fila alternos y columnas autoajustadas.

import json
from spire.xls import *

# Load JSON data
with open('C:/Users/Administrator/Desktop/employees.json') as f:
    data = json.load(f)["employees"]

if not data:
    raise ValueError("JSON data is empty!")

# Create workbook and worksheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Extract headers dynamically
headers = list(data[0].keys())
num_cols = len(headers)

# Write headers
for col, header in enumerate(headers, start=1):
    sheet.Range[1, col].Value = header

# Write rows
for row_index, item in enumerate(data, start=2):
    for col_index, key in enumerate(headers, start=1):
        value = item.get(key, "")
        sheet.Range[row_index, col_index].Value = str(value) if value is not None else ""

# Header formatting
header_row = sheet.Range[1, 1, 1, num_cols]
header_row.RowHeight = 30
header_style = header_row.Style
header_style.Font.FontName = "Times New Roman"
header_style.Font.Size = 16
header_style.Font.Color = Color.get_White()
header_style.Color = Color.FromArgb(255, 128, 128, 128)
header_style.HorizontalAlignment = HorizontalAlignType.Center
header_style.VerticalAlignment = VerticalAlignType.Center

# Data formatting
locatedRange = sheet.AllocatedRange
for rowNum in range(2, locatedRange.RowCount + 1):
    data_row = sheet.Range[rowNum, 1, rowNum, num_cols]
    data_row.RowHeight = 20
    row_style = data_row.Style
    row_style.Font.FontName = "Times New Roman"
    row_style.Font.Size = 13
    row_style.HorizontalAlignment = HorizontalAlignType.Center
    row_style.VerticalAlignment = VerticalAlignType.Center
    row_style.Color = Color.get_White() if rowNum % 2 == 0 else Color.FromArgb(255, 245, 245, 245)

# Auto-fit columns
extra_width = 3
for col in range(1, num_cols + 1):
    sheet.AutoFitColumn(col)
    current_width = sheet.Columns[col - 1].ColumnWidth
    sheet.Columns[col - 1].ColumnWidth = current_width + extra_width

workbook.SaveToFile("JsonToExcel.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Salida:

Hoja de Excel bien formateada generada por Spire.XLS

Cuándo usar este método

Ideal para la generación automatizada de informes, aplicaciones que requieren un formato preciso de Excel y flujos de trabajo donde los archivos de Excel son el entregable final.

También te puede interesar: Convertir JSON a/desde Excel en Python – Guía Completa con Ejemplos

Método 5 — Node.js con SheetJS (Flujo de Trabajo de JavaScript)

Los desarrolladores de JavaScript pueden convertir JSON a Excel utilizando bibliotecas como SheetJS. Esta biblioteca proporciona utilidades para transformar objetos JSON en hojas de cálculo y escribirlos en archivos .xlsx. Debido a que funciona bien en entornos de Node.js, se usa comúnmente en servicios de backend y scripts de procesamiento de datos.

Instalar

npm install xlsx

Ejemplo

const XLSX = require("xlsx");
const fs = require("fs");

const data = JSON.parse(fs.readFileSync("employees.json")).employees;

const worksheet = XLSX.utils.json_to_sheet(data);
const workbook = XLSX.utils.book_new();

XLSX.utils.book_append_sheet(workbook, worksheet, "Employees");
XLSX.writeFile(workbook, "output.xlsx");

Salida:

Hoja de Excel simple generada por SheetJS

Cuándo usar este método

Ideal para aplicaciones web, backends de Node.js y flujos de trabajo de automatización basados en JavaScript.

Comparación Rápida de los 5 Métodos

Cada método para convertir JSON a Excel sirve a un tipo diferente de usuario y flujo de trabajo. Algunos enfoques se centran en la simplicidad y la velocidad, mientras que otros proporcionan automatización y control de formato para escenarios más avanzados. La siguiente tabla resume las diferencias clave para ayudarte a elegir la opción más adecuada.

Método Nivel de Habilidad Automatización Ideal Para Limitaciones
Excel (Power Query) Principiante No Conversión manual rápida y exploración de datos Requiere pasos manuales; limitado para flujos de trabajo repetidos
Convertidor en Línea Principiante No Conversiones únicas y pruebas rápidas Límites de tamaño de archivo; posibles preocupaciones de privacidad
Python con pandas Intermedio Canalizaciones de datos, análisis y grandes conjuntos de datos Control limitado sobre el formato avanzado de Excel
Python con Spire.XLS Intermedio Generación de informes profesionales de Excel Requiere configuración de biblioteca adicional
Node.js con SheetJS Intermedio Aplicaciones de JavaScript y automatización de backend Requiere entorno Node.js

Mejores Prácticas para Convertir JSON a Excel

Convertir JSON a Excel puede parecer sencillo, pero los conjuntos de datos del mundo real a menudo contienen estructuras anidadas, claves inconsistentes o grandes volúmenes de datos. Seguir algunas de las mejores prácticas puede ayudar a garantizar resultados fiables y legibles.

  1. Aplanar Estructuras JSON Anidadas
  2. Muchos archivos JSON contienen objetos o arrays anidados. Si bien JSON admite datos jerárquicos, Excel funciona mejor con estructuras planas y tabulares.

    Por ejemplo, un JSON como este:

    {
      "id": 1,
      "name": "Alice",
      "address": {
        "city": "San Francisco",
        "zip": "94105"
      }
    }
    

    puede necesitar ser aplanado en:

    id nombre address.city address.zip
    1 Alice San Francisco 94105

    Bibliotecas como pandas proporcionan herramientas como json_normalize() para aplanar datos anidados automáticamente. Al trabajar con JSON más complejos, preprocesar la estructura antes de exportar a Excel a menudo produce resultados más limpios.

  3. Considera el Tamaño del Archivo y el Rendimiento

    Los grandes conjuntos de datos JSON pueden contener miles o millones de registros, lo que puede causar problemas de rendimiento al convertir directamente a Excel. Algunos consejos:

    • Usa soluciones programáticas (Python o Node.js) para archivos grandes.
    • Procesa los datos en lotes si es necesario.
    • Evita cargar conjuntos de datos extremadamente grandes directamente en Excel.

    Excel mismo tiene límites (por ejemplo, alrededor de 1,048,576 filas por hoja), por lo que los conjuntos de datos muy grandes pueden necesitar ser divididos en múltiples hojas de trabajo.

  4. Usa Múltiples Hojas para Datos Complejos
  5. Algunas API devuelven JSON con múltiples arrays relacionados, como:

    {
      "customers": [...],
      "orders": [...],
      "products": [...]
    }
    

    En lugar de forzar todo en una sola hoja de trabajo, considera exportar cada conjunto de datos a hojas de Excel separadas. Esto preserva la estructura lógica de los datos originales y facilita el análisis.

  6. Aplica Formato para una Mejor Legibilidad

    Si el archivo de Excel se compartirá con colegas o partes interesadas, el formato puede mejorar significativamente la legibilidad.

    Las prácticas de formato útiles incluyen:

    • Filas de encabezado en negrita
    • Anchos de columna ajustados
    • Colores de fila alternos
    • Fuentes y alineación consistentes

    Bibliotecas como Spire.XLS permiten el control programático sobre estos elementos, lo que permite generar informes listos para la presentación automáticamente.

Conclusión

JSON es ampliamente utilizado para almacenar e intercambiar datos estructurados, pero no siempre es ideal para el análisis o para compartir con usuarios no técnicos. Convertir JSON a Excel hace que los datos sean más fáciles de leer, filtrar y organizar en un formato de hoja de cálculo familiar.

Para conversiones simples y únicas, herramientas como Excel o convertidores en línea suelen ser suficientes. Sin embargo, los desarrolladores que trabajan con canalizaciones de datos o informes automatizados se beneficiarán de soluciones programáticas como pandas, Spire.XLS, o SheetJS, que ofrecen una mayor flexibilidad y control sobre el resultado.

Preguntas Frecuentes

P1. ¿Por qué algunos convertidores en línea rechazan JSON válido?

Muchos convertidores en línea esperan un array raíz de objetos como conjunto de datos. Si el archivo JSON comienza con un objeto raíz que contiene arrays anidados, la herramienta puede no saber qué propiedad representa la tabla. Extraer el array relevante antes de subir el archivo generalmente resuelve este problema.

P2. ¿Cuál es la diferencia entre un array JSON y un objeto JSON?

Un array JSON es una lista ordenada de valores encerrados entre corchetes [], mientras que un objeto JSON es una colección de pares clave-valor encerrados entre llaves {}.

P3. ¿Cómo puedo convertir JSON anidado a Excel?

El JSON anidado a menudo requiere ser aplanado antes de exportarlo a Excel. Herramientas como pandas proporcionan funciones como json_normalize() que expanden automáticamente los campos anidados en columnas. Alternativamente, puedes extraer manualmente objetos o arrays anidados antes de escribir los datos.

P4. ¿Puede Excel abrir archivos JSON directamente?

Sí. Excel incluye una función llamada Power Query , que puede importar archivos JSON y convertirlos en tablas. Sin embargo, el proceso puede requerir la expansión manual de estructuras anidadas para obtener un conjunto de datos tabular limpio.

También Leer

JSON in Excel umwandeln: Vollständige Anleitung

JSON ist eines der am weitesten verbreiteten Formate zum Speichern und Austauschen strukturierter Daten. APIs, Konfigurationsdateien und viele moderne Anwendungen verwenden JSON, um Datensätze darzustellen.

Allerdings ist JSON nicht immer praktisch für Analyse, Berichterstattung oder die Weitergabe an nicht-technische Benutzer. In vielen Fällen erleichtert die Konvertierung von JSON-Daten in eine Excel-Tabelle das Anzeigen, Filtern, Sortieren und Präsentieren der Informationen.

Dieser Leitfaden zeigt fünf praktische Methoden zur Konvertierung von JSON in Excel, die von No-Code-Lösungen bis hin zu programmatischen Ansätzen reichen.

Überblick über die behandelten Methoden:

Bereiten Sie Ihre JSON-Struktur vor

Bevor Sie JSON in Excel konvertieren, ist es wichtig zu verstehen, wie die Struktur Ihrer JSON-Daten den Konvertierungsprozess beeinflusst. Viele Konvertierungstools gehen von einem bestimmten Format aus, und nicht übereinstimmende Strukturen können zu unerwarteten Ergebnissen oder Fehlern führen.

Root-Array vs. Root-Objekt

Viele JSON-zu-Excel-Tools erwarten, dass die Daten ein Root-Array von Objekten sind, wie hier:

[
  {"id":1,"name":"Alice"},
  {"id":2,"name":"Bob"}
]

Diese Struktur lässt sich natürlich auf eine Excel-Tabelle abbilden:

id name
1 Alice
2 Bob

Jedes Objekt wird zu einer Zeile, und die Schlüssel werden zu Spaltenüberschriften.

Allerdings verpacken viele reale APIs und Datensätze das Array in einem Root-Objekt:

{
  "employees":[
    {"id":1,"name":"Alice"},
    {"id":2,"name":"Bob"}
  ]
}

In diesem Fall wird der eigentliche tabellarische Datensatz in der Eigenschaft "employees" gespeichert.

Warum einige Tools bei Root-Objekten fehlschlagen

Einige Konverter können nicht automatisch bestimmen, welche Eigenschaft den tabellarischen Datensatz enthält. Sie erwarten, dass die JSON-Datei direkt mit einem Array beginnt.

Wenn die Daten in einem Root-Objekt verpackt sind, können diese Tools die Datei möglicherweise nicht korrekt parsen oder leere Ergebnisse liefern.

Daher müssen Sie möglicherweise das relevante Array manuell extrahieren, bevor Sie die Konvertierung durchführen. Zum Beispiel könnten Sie die JSON-Struktur so umstrukturieren, dass das Array zum Root-Element für einen Online-Konverter wird, oder direkt im Code darauf zugreifen.

Zugriff auf das Array in Python

Wenn der Datensatz beispielsweise unter "employees" gespeichert ist, können Sie ihn wie folgt laden und extrahieren:

data = json.load(f)["employees"]

Nach diesem Schritt wird data zu einer Liste von Objekten, die leicht als Zeilen und Spalten in Excel geschrieben werden kann.

Methode 1 – Excel Power Query (ohne Code)

Wenn Sie bereits Microsoft Excel installiert haben, können Sie JSON-Daten direkt importieren, ohne Code zu schreiben. Die Funktion Power Query von Excel ermöglicht es Benutzern, JSON-Dateien zu laden und sie automatisch in ein tabellarisches Format zu konvertieren. Dieser Ansatz ist ideal für Analysten oder Geschäftsanwender, die JSON-Daten schnell in einer Tabellenkalkulationsumgebung anzeigen möchten.

Schritte

  1. Starten Sie Microsoft Excel auf Ihrem Computer.
  2. Klicken Sie auf die Registerkarte Daten im oberen Menü von Excel.
  3. Navigieren Sie in der Registerkarte Daten zu Daten abrufen, wählen Sie dann Aus Datei und wählen Sie Aus JSON aus dem Dropdown-Menü.
  4. Daten aus JSON-Datei abrufen

  5. Wenn Sie dazu aufgefordert werden, suchen und wählen Sie Ihre JSON-Datei aus und klicken Sie dann auf Importieren.
  6. Der Power Query-Editor wird gestartet.
  7. Power Query-Editor

  8. Wenn die Datei als eine Liste von Datensätzen geöffnet wird:

    • Klicken Sie auf Zur Tabelle, um die Liste in ein Tabellenformat zu konvertieren.
    • Liste in Tabelle umwandeln

    • Klicken Sie dann auf das Erweitern (⇄)-Symbol in der Spaltenüberschrift, um die Spaltennamen anzuzeigen. Wenn die Spalten immer noch "Liste" oder "Datensatz" anzeigen, klicken Sie erneut auf das Erweiterungssymbol, um weiter zu reduzieren.
    • Listen oder Datensätze erweitern

    • Ein Dialogfeld wird angezeigt, in dem Sie auswählen können, welche Felder Sie in die Tabelle aufnehmen möchten. Wählen Sie die erforderlichen Felder aus, deaktivieren Sie "Ursprünglichen Spaltennamen als Präfix verwenden" für sauberere Überschriften und klicken Sie dann auf OK.
    • Die erforderlichen Felder auswählen

  9. Klicken Sie auf Schließen & Laden, um die strukturierten Daten in Ihr Excel-Arbeitsblatt zu importieren.
  10. Strukturierte Daten in Arbeitsblatt laden

  11. Speichern Sie Ihre Excel-Datei im .xlsx-Format, um sicherzustellen, dass Ihre Daten für die zukünftige Verwendung erhalten bleiben.

Wann diese Methode verwenden

Am besten für kleine Datensätze und Benutzer, die eine visuelle Oberfläche anstelle von Programmierung bevorzugen.

Methode 2 – Online-JSON-Konverter (schnell und einmalig)

Online-JSON-Konverter bieten eine der schnellsten Möglichkeiten, JSON-Dateien in Excel-Tabellen umzuwandeln. Diese Tools erfordern in der Regel nur einen Dateiupload und generieren automatisch eine herunterladbare Excel-Datei. Plattformen wie die von jsontoexcel.net können die Konvertierung in Sekunden abschließen, ohne dass Software installiert werden muss.

Schritte

  1. Öffnen Sie eine JSON-zu-Excel-Konverter-Website.
  2. Kopieren Sie Ihre JSON-Daten und fügen Sie sie direkt in den Texteditor ein oder laden Sie eine Datei von Ihrem Computer hoch.
  3. Json-Daten einfügen oder Json in Online-Konverter laden

  4. Klicken Sie auf die Schaltfläche In Excel konvertieren, um den Konvertierungsprozess zu starten.
  5. Laden Sie die generierte Excel-Datei herunter.
  6. Die generierte Excel-Datei herunterladen

Wichtiger Hinweis

Die meisten Online-Konverter erwarten ein Root-Array von Objekten; andernfalls können sie stillschweigend fehlschlagen oder unerwartete Ergebnisse liefern. Dieses Format lässt sich am zuverlässigsten in Excel konvertieren.

Wann diese Methode verwenden

Am besten für schnelle, einmalige Konvertierungen oder zum Testen von Beispieldatensätzen.

Methode 3 – Python mit Pandas (automatisierungsfreundlich)

Für Entwickler und Dateningenieure bietet Python eine leistungsstarke Möglichkeit, JSON-zu-Excel-Konvertierungen zu automatisieren. Die beliebte Datenanalysebibliothek pandas kann problemlos JSON-Dateien laden, sie in einen strukturierten DataFrame umwandeln und die Ergebnisse nach Excel exportieren. Diese Methode ist besonders nützlich, wenn die Konvertierung in Skripte, ETL-Workflows oder automatisierte Berichtspipelines integriert werden muss.

Abhängigkeiten installieren

pip install pandas openpyxl

JSON in Excel konvertieren

import pandas as pd
import json

with open("employees.json") as f:
    data = json.load(f)["employees"]

df = pd.json_normalize(data)
df.to_excel("output.xlsx", index=False)

Ausgabe:

Einfaches Excel-Blatt, generiert von Pandas

Wann diese Methode verwenden

Ideal für die automatisierte Datenverarbeitung, Analyse-Workflows und große Datensätze.

Methode 4 – Python mit Spire.XLS (formatierte Excel-Berichte)

Wenn Ihr Ziel darin besteht, gut formatierte Excel-Berichte zu erstellen, kann Python mit Spire.XLS zusammenarbeiten, um Tabellenkalkulationen programmgesteuert zu erstellen. Im Gegensatz zu einfachen Datenexportbibliotheken bietet Spire.XLS eine umfassende Kontrolle über die Excel-Formatierung, einschließlich Schriftarten, Farben, Ausrichtung und Spaltengrößen. Dies macht es geeignet für die Erstellung professioneller Tabellenkalkulationen, die bereit sind, mit Stakeholdern geteilt zu werden.

Die Bibliothek installieren

pip install spire.xls

Beispielcode

Das folgende Skript liest JSON-Mitarbeiterdaten, generiert dynamisch Spaltenüberschriften, schreibt Zeilen in Excel und wendet Formatierungen wie Kopfzeilen-Styling, abwechselnde Zeilenfarben und automatisch angepasste Spalten an.

import json
from spire.xls import *

# Load JSON data
with open('C:/Users/Administrator/Desktop/employees.json') as f:
    data = json.load(f)["employees"]

if not data:
    raise ValueError("JSON data is empty!")

# Create workbook and worksheet
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Extract headers dynamically
headers = list(data[0].keys())
num_cols = len(headers)

# Write headers
for col, header in enumerate(headers, start=1):
    sheet.Range[1, col].Value = header

# Write rows
for row_index, item in enumerate(data, start=2):
    for col_index, key in enumerate(headers, start=1):
        value = item.get(key, "")
        sheet.Range[row_index, col_index].Value = str(value) if value is not None else ""

# Header formatting
header_row = sheet.Range[1, 1, 1, num_cols]
header_row.RowHeight = 30
header_style = header_row.Style
header_style.Font.FontName = "Times New Roman"
header_style.Font.Size = 16
header_style.Font.Color = Color.get_White()
header_style.Color = Color.FromArgb(255, 128, 128, 128)
header_style.HorizontalAlignment = HorizontalAlignType.Center
header_style.VerticalAlignment = VerticalAlignType.Center

# Data formatting
locatedRange = sheet.AllocatedRange
for rowNum in range(2, locatedRange.RowCount + 1):
    data_row = sheet.Range[rowNum, 1, rowNum, num_cols]
    data_row.RowHeight = 20
    row_style = data_row.Style
    row_style.Font.FontName = "Times New Roman"
    row_style.Font.Size = 13
    row_style.HorizontalAlignment = HorizontalAlignType.Center
    row_style.VerticalAlignment = VerticalAlignType.Center
    row_style.Color = Color.get_White() if rowNum % 2 == 0 else Color.FromArgb(255, 245, 245, 245)

# Auto-fit columns
extra_width = 3
for col in range(1, num_cols + 1):
    sheet.AutoFitColumn(col)
    current_width = sheet.Columns[col - 1].ColumnWidth
    sheet.Columns[col - 1].ColumnWidth = current_width + extra_width

workbook.SaveToFile("JsonToExcel.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Ausgabe:

Gut formatiertes Excel-Blatt, generiert von Spire.XLS

Wann diese Methode verwenden

Am besten für die automatisierte Berichterstellung, Anwendungen, die eine präzise Excel-Formatierung erfordern, und Workflows, bei denen Excel-Dateien das Endergebnis sind.

Das könnte Ihnen auch gefallen: JSON in/aus Excel in Python konvertieren – Vollständiger Leitfaden mit Beispielen

Methode 5 – Node.js mit SheetJS (JavaScript-Workflow)

JavaScript-Entwickler können JSON mit Bibliotheken wie SheetJS in Excel konvertieren. Diese Bibliothek bietet Dienstprogramme zum Umwandeln von JSON-Objekten in Tabellenkalkulationsblätter und zum Schreiben in .xlsx-Dateien. Da es gut in Node.js-Umgebungen funktioniert, wird es häufig in Backend-Diensten und Datenverarbeitungsskripten verwendet.

Installieren

npm install xlsx

Beispiel

const XLSX = require("xlsx");
const fs = require("fs");

const data = JSON.parse(fs.readFileSync("employees.json")).employees;

const worksheet = XLSX.utils.json_to_sheet(data);
const workbook = XLSX.utils.book_new();

XLSX.utils.book_append_sheet(workbook, worksheet, "Employees");
XLSX.writeFile(workbook, "output.xlsx");

Ausgabe:

Einfaches Excel-Blatt, generiert von SheetJS

Wann diese Methode verwenden

Am besten für Webanwendungen, Node.js-Backends und JavaScript-basierte Automatisierungsworkflows.

Schneller Vergleich der 5 Methoden

Jede Methode zur Konvertierung von JSON in Excel richtet sich an einen anderen Benutzertyp und Workflow. Einige Ansätze konzentrieren sich auf Einfachheit und Geschwindigkeit, während andere Automatisierung und Formatierungskontrolle für fortgeschrittenere Szenarien bieten. Die folgende Tabelle fasst die wichtigsten Unterschiede zusammen, um Ihnen bei der Auswahl der am besten geeigneten Option zu helfen.

Methode Fähigkeitslevel Automatisierung Am besten für Einschränkungen
Excel (Power Query) Anfänger Nein Schnelle manuelle Konvertierung und Datenexploration Erfordert manuelle Schritte; begrenzt für wiederholte Workflows
Online-Konverter Anfänger Nein Einmalige Konvertierungen und schnelle Tests Dateigrößenbeschränkungen; potenzielle Datenschutzbedenken
Python mit Pandas Mittelstufe Ja Datenpipelines, Analysen und große Datensätze Begrenzte Kontrolle über erweiterte Excel-Formatierung
Python mit Spire.XLS Mittelstufe Ja Erstellung professioneller Excel-Berichte Erfordert zusätzliche Bibliotheks-Einrichtung
Node.js mit SheetJS Mittelstufe Ja JavaScript-Anwendungen und Backend-Automatisierung Erfordert Node.js-Umgebung

Bewährte Verfahren zum Konvertieren von JSON in Excel

Die Konvertierung von JSON in Excel mag unkompliziert erscheinen, aber reale Datensätze enthalten oft verschachtelte Strukturen, inkonsistente Schlüssel oder große Datenmengen. Das Befolgen einiger bewährter Verfahren kann helfen, zuverlässige und lesbare Ergebnisse zu gewährleisten.

  1. Verschachtelte JSON-Strukturen abflachen
  2. Viele JSON-Dateien enthalten verschachtelte Objekte oder Arrays. Während JSON hierarchische Daten unterstützt, funktioniert Excel am besten mit flachen, tabellarischen Strukturen.

    Zum Beispiel JSON wie dieses:

    {
      "id": 1,
      "name": "Alice",
      "address": {
        "city": "San Francisco",
        "zip": "94105"
      }
    }
    

    muss möglicherweise abgeflacht werden in:

    id name address.city address.zip
    1 Alice San Francisco 94105

    Bibliotheken wie Pandas bieten Tools wie json_normalize(), um verschachtelte Daten automatisch abzuflachen. Bei der Arbeit mit komplexerem JSON führt die Vorverarbeitung der Struktur vor dem Export nach Excel oft zu saubereren Ergebnissen.

  3. Dateigröße und Leistung berücksichtigen

    Große JSON-Datensätze können Tausende oder Millionen von Datensätzen enthalten, was bei der direkten Konvertierung in Excel zu Leistungsproblemen führen kann. Einige Tipps:

    • Verwenden Sie programmatische Lösungen (Python oder Node.js) für große Dateien.
    • Verarbeiten Sie die Daten bei Bedarf in Stapeln.
    • Vermeiden Sie das direkte Laden extrem großer Datensätze in Excel.

    Excel selbst hat Grenzen (zum Beispiel etwa 1.048.576 Zeilen pro Blatt), sodass sehr große Datensätze möglicherweise auf mehrere Arbeitsblätter aufgeteilt werden müssen.

  4. Verwenden Sie mehrere Blätter für komplexe Daten
  5. Einige APIs geben JSON mit mehreren zusammengehörigen Arrays zurück, wie zum Beispiel:

    {
      "customers": [...],
      "orders": [...],
      "products": [...]
    }
    

    Anstatt alles in ein Arbeitsblatt zu zwingen, sollten Sie jeden Datensatz in separate Excel-Blätter exportieren. Dies bewahrt die logische Struktur der ursprünglichen Daten und erleichtert die Analyse.

  6. Formatierung für bessere Lesbarkeit anwenden

    Wenn die Excel-Datei mit Kollegen oder Stakeholdern geteilt wird, kann die Formatierung die Lesbarkeit erheblich verbessern.

    Nützliche Formatierungspraktiken umfassen:

    • Fettgedruckte Kopfzeilen
    • Angepasste Spaltenbreiten
    • Abwechselnde Zeilenfarben
    • Konsistente Schriftarten und Ausrichtung

    Bibliotheken wie Spire.XLS ermöglichen die programmgesteuerte Kontrolle über diese Elemente, sodass präsentationsfertige Berichte automatisch erstellt werden können.

Fazit

JSON wird häufig zum Speichern und Austauschen strukturierter Daten verwendet, ist aber nicht immer ideal für die Analyse oder die Weitergabe an nicht-technische Benutzer. Die Konvertierung von JSON in Excel macht die Daten in einem vertrauten Tabellenkalkulationsformat leichter lesbar, filterbar und organisierbar.

Für einfache, einmalige Konvertierungen sind Tools wie Excel oder Online-Konverter oft ausreichend. Entwickler, die mit Datenpipelines oder automatisierten Berichten arbeiten, profitieren jedoch von programmatischen Lösungen wie pandas, Spire.XLS oder SheetJS, die eine größere Flexibilität und Kontrolle über die Ausgabe bieten.

Häufig gestellte Fragen

F1. Warum lehnen einige Online-Konverter gültiges JSON ab?

Viele Online-Konverter erwarten ein Root-Array von Objekten als Datensatz. Wenn die JSON-Datei mit einem Root-Objekt beginnt, das verschachtelte Arrays enthält, weiß das Tool möglicherweise nicht, welche Eigenschaft die Tabelle darstellt. Das Extrahieren des relevanten Arrays vor dem Hochladen der Datei löst dieses Problem normalerweise.

F2. Was ist der Unterschied zwischen einem JSON-Array und einem JSON-Objekt?

Ein JSON-Array ist eine geordnete Liste von Werten, die in eckigen Klammern [] eingeschlossen sind, während ein JSON-Objekt eine Sammlung von Schlüssel-Wert-Paaren ist, die in geschweiften Klammern {} eingeschlossen sind.

F3. Wie kann ich verschachteltes JSON in Excel konvertieren?

Verschachteltes JSON erfordert oft ein Abflachen vor dem Export nach Excel. Tools wie Pandas bieten Funktionen wie json_normalize(), die verschachtelte Felder automatisch in Spalten erweitern. Alternativ können Sie verschachtelte Objekte oder Arrays manuell extrahieren, bevor Sie die Daten schreiben.

F4. Kann Excel JSON-Dateien direkt öffnen?

Ja. Excel enthält eine Funktion namens Power Query, die JSON-Dateien importieren und in Tabellen umwandeln kann. Der Prozess kann jedoch das manuelle Erweitern verschachtelter Strukturen erfordern, um einen sauberen tabellarischen Datensatz zu erhalten.

Lesen Sie auch

Преобразование JSON в Excel: полное руководство

JSON — один из самых широко используемых форматов для хранения и обмена структурированными данными. API, файлы конфигурации и многие современные приложения используют JSON для представления наборов данных.

Однако JSON не всегда удобен для анализа, создания отчетов или обмена с нетехническими пользователями. Во многих случаях преобразование данных JSON в электронную таблицу Excel упрощает просмотр, фильтрацию, сортировку и представление информации.

В этом руководстве показаны пять практических методов преобразования JSON в Excel, от решений без кода до программных подходов.

Обзор рассматриваемых методов:

Подготовьте свою структуру JSON

Перед преобразованием JSON в Excel важно понять, как структура ваших данных JSON влияет на процесс преобразования. Многие инструменты преобразования предполагают определенный формат, и несоответствие структур может привести к неожиданным результатам или ошибкам.

Корневой массив и корневой объект

Многие инструменты для преобразования JSON в Excel ожидают, что данные будут представлять собой корневой массив объектов, например:

[
  {"id":1,"name":"Алиса"},
  {"id":2,"name":"Боб"}
]

Эта структура естественным образом сопоставляется с таблицей Excel:

id имя
1 Алиса
2 Боб

Каждый объект становится строкой, а ключи — заголовками столбцов.

Однако многие реальные API и наборы данных заключают массив в корневой объект:

{
  "employees":[
    {"id":1,"name":"Алиса"},
    {"id":2,"name":"Боб"}
  ]
}

В этом случае фактический табличный набор данных хранится в свойстве "employees".

Почему некоторые инструменты не работают с корневыми объектами

Некоторые конвертеры не могут автоматически определить, какое свойство содержит табличный набор данных. Они ожидают, что JSON-файл будет начинаться непосредственно с массива.

Когда данные заключены в корневой объект, эти инструменты могут неверно проанализировать файл или выдать пустые результаты.

Поэтому вам может потребоваться извлечь соответствующий массив вручную перед выполнением преобразования. Например, вы можете реструктурировать JSON так, чтобы массив стал корневым элементом для онлайн-конвертера, или получить к нему доступ непосредственно в коде.

Доступ к массиву в Python

Например, если набор данных хранится в "employees", вы можете загрузить и извлечь его следующим образом:

data = json.load(f)["employees"]

После этого шага data становится списком объектов, которые можно легко записать в Excel в виде строк и столбцов.

Метод 1 — Excel Power Query (без кода)

Если у вас уже установлен Microsoft Excel, вы можете импортировать данные JSON напрямую, не написав ни строчки кода. Функция Power Query в Excel позволяет пользователям загружать файлы JSON и автоматически преобразовывать их в табличный формат. Этот подход идеален для аналитиков или бизнес-пользователей, которые хотят быстро просматривать данные JSON в среде электронных таблиц.

Шаги

  1. Запустите Microsoft Excel на своем компьютере.
  2. Перейдите на вкладку Данные, расположенную в верхнем меню Excel.
  3. На вкладке "Данные" перейдите к Получить данные, затем выберите Из файла и выберите Из JSON в раскрывающемся меню.
  4. Получить данные из файла JSON

  5. Когда появится запрос, найдите и выберите свой JSON-файл, затем нажмите Импорт.
  6. Запустится редактор Power Query.
  7. Редактор Power Query

  8. Если файл открывается как список записей:

    • Нажмите В таблицу, чтобы преобразовать список в табличный формат.
    • Преобразовать список в таблицу

    • Затем щелкните значок Развернуть (⇄) в заголовке столбца, чтобы отобразить имена столбцов. Если в столбцах по-прежнему отображается "Список" или "Запись," щелкните значок развертывания еще раз, чтобы продолжить сведение.
    • Развернуть списки или записи

    • Появится диалоговое окно, в котором вы сможете выбрать, какие поля вы хотите включить в таблицу. Выберите необходимые поля, снимите флажок "Использовать исходное имя столбца как префикс" для более чистых заголовков, а затем нажмите ОК.
    • Выберите необходимые поля

  9. Нажмите Закрыть и загрузить, чтобы импортировать структурированные данные в лист Excel.
  10. Загрузить структурированные данные в лист

  11. Сохраните файл Excel в формате .xlsx, чтобы ваши данные сохранились для будущего использования.

Когда использовать этот метод

Лучше всего подходит для небольших наборов данных и пользователей, которые предпочитают визуальный интерфейс программированию.

Метод 2 — Онлайн-конвертер JSON (для разовых задач)

Онлайн-конвертеры JSON предоставляют один из самых быстрых способов превратить файлы JSON в электронные таблицы Excel. Эти инструменты обычно требуют только загрузки файла и автоматически создают загружаемый файл Excel. Платформы, подобные тем, что предлагает jsontoexcel.net, могут выполнить преобразование за считанные секунды без установки какого-либо программного обеспечения.

Шаги

  1. Откройте веб-сайт конвертера JSON в Excel.
  2. Скопируйте и вставьте данные JSON непосредственно в текстовый редактор или загрузите файл с вашего компьютера.
  3. Вставьте данные Json или загрузите Json в онлайн-конвертер

  4. Нажмите кнопку Конвертировать в Excel, чтобы начать процесс преобразования.
  5. Загрузите сгенерированный файл Excel.
  6. Загрузите сгенерированный файл Excel

Важное замечание

Большинство онлайн-конвертеров ожидают корневой массив объектов; в противном случае они могут молча завершиться неудачей или выдать неожиданные результаты. Этот формат наиболее надежно преобразуется в Excel.

Когда использовать этот метод

Лучше всего подходит для быстрых, одноразовых преобразований или тестирования образцов наборов данных.

Метод 3 — Python с pandas (удобно для автоматизации)

Для разработчиков и инженеров данных Python предоставляет мощный способ автоматизации преобразования JSON в Excel. Популярная библиотека для анализа данных pandas может легко загружать файлы JSON, преобразовывать их в структурированный DataFrame и экспортировать результаты в Excel. Этот метод особенно полезен, когда преобразование необходимо интегрировать в скрипты, рабочие процессы ETL или автоматизированные конвейеры отчетности.

Установка зависимостей

pip install pandas openpyxl

Преобразование JSON в Excel

import pandas as pd
import json

with open("employees.json") as f:
    data = json.load(f)["employees"]

df = pd.json_normalize(data)
df.to_excel("output.xlsx", index=False)

Вывод:

Простой лист Excel, сгенерированный pandas

Когда использовать этот метод

Идеально подходит для автоматизированной обработки данных, аналитических рабочих процессов и больших наборов данных.

Метод 4 — Python с Spire.XLS (для форматированных отчетов Excel)

Если ваша цель — создавать хорошо отформатированные отчеты Excel, Python может работать с Spire.XLS для программного создания электронных таблиц. В отличие от простых библиотек экспорта данных, Spire.XLS предоставляет обширный контроль над форматированием Excel, включая шрифты, цвета, выравнивание и размеры столбцов. Это делает его подходящим для создания профессиональных электронных таблиц, готовых для обмена с заинтересованными сторонами.

Установите библиотеку

pip install spire.xls

Пример кода

Следующий скрипт считывает данные о сотрудниках в формате JSON, динамически генерирует заголовки столбцов, записывает строки в Excel и применяет форматирование, такое как стиль заголовка, чередующиеся цвета строк и автоматически подогнанные столбцы.

import json
from spire.xls import *

# Загрузка данных JSON
with open('C:/Users/Administrator/Desktop/employees.json') as f:
    data = json.load(f)["employees"]

if not data:
    raise ValueError("Данные JSON пусты!")

# Создание книги и листа
workbook = Workbook()
sheet = workbook.Worksheets[0]

# Динамическое извлечение заголовков
headers = list(data[0].keys())
num_cols = len(headers)

# Запись заголовков
for col, header in enumerate(headers, start=1):
    sheet.Range[1, col].Value = header

# Запись строк
for row_index, item in enumerate(data, start=2):
    for col_index, key in enumerate(headers, start=1):
        value = item.get(key, "")
        sheet.Range[row_index, col_index].Value = str(value) if value is not None else ""

# Форматирование заголовка
header_row = sheet.Range[1, 1, 1, num_cols]
header_row.RowHeight = 30
header_style = header_row.Style
header_style.Font.FontName = "Times New Roman"
header_style.Font.Size = 16
header_style.Font.Color = Color.get_White()
header_style.Color = Color.FromArgb(255, 128, 128, 128)
header_style.HorizontalAlignment = HorizontalAlignType.Center
header_style.VerticalAlignment = VerticalAlignType.Center

# Форматирование данных
locatedRange = sheet.AllocatedRange
for rowNum in range(2, locatedRange.RowCount + 1):
    data_row = sheet.Range[rowNum, 1, rowNum, num_cols]
    data_row.RowHeight = 20
    row_style = data_row.Style
    row_style.Font.FontName = "Times New Roman"
    row_style.Font.Size = 13
    row_style.HorizontalAlignment = HorizontalAlignType.Center
    row_style.VerticalAlignment = VerticalAlignType.Center
    row_style.Color = Color.get_White() if rowNum % 2 == 0 else Color.FromArgb(255, 245, 245, 245)

# Автоподбор ширины столбцов
extra_width = 3
for col in range(1, num_cols + 1):
    sheet.AutoFitColumn(col)
    current_width = sheet.Columns[col - 1].ColumnWidth
    sheet.Columns[col - 1].ColumnWidth = current_width + extra_width

workbook.SaveToFile("JsonToExcel.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Вывод:

Хорошо отформатированный лист Excel, сгенерированный Spire.XLS

Когда использовать этот метод

Лучше всего подходит для автоматического создания отчетов, приложений, требующих точного форматирования Excel, и рабочих процессов, где файлы Excel являются конечным результатом.

Вам также может понравиться: Преобразование JSON в/из Excel на Python — полное руководство с примерами

Метод 5 — Node.js с SheetJS (рабочий процесс на JavaScript)

Разработчики JavaScript могут преобразовывать JSON в Excel с помощью таких библиотек, как SheetJS. Эта библиотека предоставляет утилиты для преобразования объектов JSON в листы электронных таблиц и их записи в файлы .xlsx. Поскольку она хорошо работает в средах Node.js, она обычно используется в бэкэнд-сервисах и скриптах обработки данных.

Установка

npm install xlsx

Пример

const XLSX = require("xlsx");
const fs = require("fs");

const data = JSON.parse(fs.readFileSync("employees.json")).employees;

const worksheet = XLSX.utils.json_to_sheet(data);
const workbook = XLSX.utils.book_new();

XLSX.utils.book_append_sheet(workbook, worksheet, "Employees");
XLSX.writeFile(workbook, "output.xlsx");

Вывод:

Простой лист Excel, сгенерированный SheetJS

Когда использовать этот метод

Лучше всего подходит для веб-приложений, бэкендов Node.js и рабочих процессов автоматизации на основе JavaScript.

Краткое сравнение 5 методов

Каждый метод преобразования JSON в Excel предназначен для разных типов пользователей и рабочих процессов. Некоторые подходы ориентированы на простоту и скорость, в то время как другие обеспечивают автоматизацию и контроль форматирования для более сложных сценариев. В таблице ниже приведены основные различия, которые помогут вам выбрать наиболее подходящий вариант.

Метод Уровень квалификации Автоматизация Лучше всего для Ограничения
Excel (Power Query) Начинающий Нет Быстрое ручное преобразование и исследование данных Требует ручных шагов; ограничен для повторяющихся рабочих процессов
Онлайн-конвертер Начинающий Нет Одноразовые преобразования и быстрое тестирование Ограничения на размер файла; потенциальные проблемы с конфиденциальностью
Python с pandas Средний Да Конвейеры данных, аналитика и большие наборы данных Ограниченный контроль над расширенным форматированием Excel
Python с Spire.XLS Средний Да Создание профессиональных отчетов Excel Требуется дополнительная настройка библиотеки
Node.js с SheetJS Средний Да Приложения JavaScript и автоматизация бэкенда Требуется среда Node.js

Лучшие практики по преобразованию JSON в Excel

Преобразование JSON в Excel может показаться простым, но реальные наборы данных часто содержат вложенные структуры, несогласованные ключи или большие объемы данных. Соблюдение нескольких лучших практик поможет обеспечить надежные и читаемые результаты.

  1. Сведение вложенных структур JSON
  2. Многие файлы JSON содержат вложенные объекты или массивы. Хотя JSON поддерживает иерархические данные, Excel лучше всего работает с плоскими, табличными структурами.

    Например, такой JSON:

    {
      "id": 1,
      "name": "Алиса",
      "address": {
        "city": "Сан-Франциско",
        "zip": "94105"
      }
    }
    

    может потребоваться свести к:

    id имя address.city address.zip
    1 Алиса Сан-Франциско 94105

    Библиотеки, такие как pandas, предоставляют инструменты, подобные json_normalize(), для автоматического сведения вложенных данных. При работе с более сложным JSON предварительная обработка структуры перед экспортом в Excel часто дает более чистые результаты.

  3. Учитывайте размер файла и производительность

    Большие наборы данных JSON могут содержать тысячи или миллионы записей, что может вызвать проблемы с производительностью при прямом преобразовании в Excel. Несколько советов:

    • Используйте программные решения (Python или Node.js) для больших файлов.
    • При необходимости обрабатывайте данные пакетами.
    • Избегайте загрузки чрезвычайно больших наборов данных непосредственно в Excel.

    Сам Excel имеет ограничения (например, около 1 048 576 строк на лист), поэтому очень большие наборы данных может потребоваться разделить на несколько листов.

  4. Используйте несколько листов для сложных данных
  5. Некоторые API возвращают JSON с несколькими связанными массивами, например:

    {
      "customers": [...],
      "orders": [...],
      "products": [...]
    }
    

    Вместо того, чтобы помещать все в один лист, рассмотрите возможность экспорта каждого набора данных в отдельные листы Excel. Это сохраняет логическую структуру исходных данных и упрощает анализ.

  6. Применяйте форматирование для лучшей читаемости

    Если файл Excel будет передаваться коллегам или заинтересованным сторонам, форматирование может значительно улучшить читаемость.

    Полезные практики форматирования включают:

    • Выделение строк заголовков жирным шрифтом
    • Скорректированная ширина столбцов
    • Чередующиеся цвета строк
    • Единообразные шрифты и выравнивание

    Библиотеки, подобные Spire.XLS, позволяют программно управлять этими элементами, что дает возможность автоматически создавать готовые к презентации отчеты.

Заключение

JSON широко используется для хранения и обмена структурированными данными, но он не всегда идеален для анализа или обмена с нетехническими пользователями. Преобразование JSON в Excel упрощает чтение, фильтрацию и организацию данных в привычном формате электронной таблицы.

Для простых, одноразовых преобразований часто достаточно таких инструментов, как Excel или онлайн-конвертеры. Однако разработчики, работающие с конвейерами данных или автоматизированными отчетами, получат выгоду от программных решений, таких как pandas, Spire.XLS или SheetJS, которые предлагают большую гибкость и контроль над выводом.

Часто задаваемые вопросы

В1. Почему некоторые онлайн-конвертеры отклоняют действительный JSON?

Многие онлайн-конвертеры ожидают корневой массив объектов в качестве набора данных. Если JSON-файл начинается с корневого объекта, содержащего вложенные массивы, инструмент может не знать, какое свойство представляет таблицу. Извлечение соответствующего массива перед загрузкой файла обычно решает эту проблему.

В2. В чем разница между массивом JSON и объектом JSON?

Массив JSON — это упорядоченный список значений, заключенный в квадратные скобки [], а объект JSON — это коллекция пар ключ-значение, заключенная в фигурные скобки {}.

В3. Как я могу преобразовать вложенный JSON в Excel?

Вложенный JSON часто требует сведения перед экспортом в Excel. Инструменты, такие как pandas, предоставляют функции, подобные json_normalize(), которые автоматически разворачивают вложенные поля в столбцы. В качестве альтернативы вы можете вручную извлечь вложенные объекты или массивы перед записью данных.

В4. Может ли Excel открывать файлы JSON напрямую?

Да. В Excel есть функция под названием Power Query , которая может импортировать файлы JSON и преобразовывать их в таблицы. Однако процесс может потребовать ручного развертывания вложенных структур для получения чистого табличного набора данных.

Также читайте

cover page of converting powerpoint to ofd

Page Content:

PowerPoint presentations are widely used for business reports and technical documentation. In some industries, especially in government and enterprise systems, documents are often required to be distributed in OFD instead of standard Office formats. Because PowerPoint files can include complex layouts and interactive elements, they are not always suitable for standardized document distribution.

In this tutorial, you will learn how to convert PowerPoint to OFD in C++ using Spire.Presentation for C++. The guide walks through simple code examples for converting an entire .ppt/.pptx file, exporting a single slide, and performing batch PPT to OFD conversion for multiple files.

Differences between PowerPoint and OFD Format

Before implementing the conversion, it helps to first understand the key differences between PowerPoint and OFD formats. Each format is designed for a different purpose and usage scenario, which is why some organizations require documents to be converted before distribution. Knowing these differences can make it clearer why converting PowerPoint to OFD is often necessary in enterprise or government document workflows.

1. File Structure and Purpose

PowerPoint files (PPT/PPTX) are designed for interactive presentations and support animations, transitions, embedded media, and editable slide elements.

OFD, in contrast, is a fixed layout document format like PDF, designed to preserve the exact visual layout of a document across different systems. Because of this, OFD is commonly used for official document distribution and long-term digital archiving.

OFD, in contrast, is a fixed layout document format like PDF, designed to preserve the exact visual layout of a document across different systems. Because of this, OFD is commonly used for official document distribution and long-term digital archiving, similar to scenarios where organizations convert PowerPoint to PDF to ensure consistent document formatting.

2. Compatibility and Standardization

PowerPoint belongs to the Microsoft Office ecosystem and typically requires compatible presentation software to view or edit.

OFD is an open national standard created for electronic document exchange, allowing organizations to share and store documents with consistent formatting regardless of the software environment.

3. Security and Compliance

In many enterprise and government workflows, documents must follow standardized formats to meet regulatory requirements. OFD supports features such as digital signatures, fixed layout rendering, and secure document exchange, making it suitable for compliant document distribution.

How to Convert PowerPoint to OFD with Spire.Presentation for C++

Understanding the differences between PowerPoint and OFD is the first step in ensuring documents are properly formatted for distribution. OFD’s fixed layout and standardized features make it ideal for official and long-term archival use.

To handle the conversion in C++, Spire.Presentation for C++ provides a simple and reliable solution. It lets developers load, edit, and export PowerPoint files to OFD while preserving the original layout and content. It also supports other tasks such as editing slides, extracting images, and converting PowerPoint files to images and other formats.

Read on to learn how to use Spire.Presentation for C++ to convert PowerPoint to OFD format.

Install Spire.Presentation for C++:

Before using the sample code in Visual Studio, make sure to add the library to your C++ project. You can either download it from the official download link and add it to your project manually, or install it automatically via NuGet.

For a more detailed tutorial on how to integrate Spire.Presentation for C++, see: How to Integrate Spire.Presentation for C++ in a C++ Application.

PowerPoint to OFD Conversion Workflow:

  • Specify the input and output file paths.
  • Create a Presentation object.
  • Load the PowerPoint file using Presentation.LoadFromFile(String).
  • Save the presentation as an OFD file using Presentation.SaveToFile(String, FileFormat).
  • Dispose of the Presentation object to release resources.

Sample Code:

#include "Spire.Presentation.o.h";

using namespace Spire::Presentation;
using namespace std;

int main()
{
    // Specify the input and output file paths
    std::wstring inputFile = L"powerpoint-sample.pptx";
    std::wstring outputFile = L"output\\PowerPointToOFD.ofd";

    // Create a Presentation object
    intrusive_ptr<Presentation> presentation = new Presentation();

    // Load a PowerPoint document from disk
    presentation->LoadFromFile(inputFile.c_str());

    // Save the document to OFD format
    presentation->SaveToFile(outputFile.c_str(), FileFormat::OFD);

    presentation->Dispose();

}

Conversion Result:

conversion result of using spire presentation for c++ to convert powerpoint to ofd format

Note: If you want to remove the evaluation warning message of the converted OFD file or gain full access to all features of Spire.Presentation for C++, please contact us to request a 30-day trial license.

Batch Convert PowerPoint Files into OFD Format with C++

In real-world development scenarios, developers often need to process multiple PowerPoint files at once rather than converting them individually. For example, a document management system may need to convert a folder of PPT files into OFD format for standardized archiving or distribution.

Using Spire.Presentation for C++, you can easily iterate through a directory, load each PowerPoint file, and export it to OFD format automatically. This approach greatly improves efficiency when handling large numbers of presentations.

Batch PowerPoint to OFD Conversion Workflow

  • Specify the input folder containing PowerPoint files and the output folder for the converted OFD files.
  • Iterate through all files in the input directory.
  • Load each PowerPoint file using the Presentation object.
  • Generate a corresponding OFD output file path.
  • Save the presentation as an OFD file.
  • Dispose of the Presentation object to release resources.

Sample Code:

#include "Spire.Presentation.o.h"
#include <filesystem>

using namespace Spire::Presentation;
using namespace std;
namespace fs = std::filesystem;

int main()
{
    // Specify folder paths
    wstring inputFolder = L"InputPPT";
    wstring outputFolder = L"batchoutputOFD";

    for (auto& file : fs::directory_iterator(inputFolder))
    {
        if (file.path().extension() == L".pptx")
        {
            intrusive_ptr<Presentation> presentation = new Presentation();

            // Load PowerPoint file
            presentation->LoadFromFile(file.path().wstring().c_str());

            // Generate output OFD file path
            wstring outputFile = outputFolder + L"\\" + file.path().stem().wstring() + L".ofd";

            // Convert to OFD
            presentation->SaveToFile(outputFile.c_str(), FileFormat::OFD);

            presentation->Dispose();
        }
    }

    return 0;
}

Convert a Single Slide of PowerPoint to OFD with C++

In some scenarios, developers may only need to export selected slides instead of converting the entire presentation. For example, a reporting system may generate an OFD document from only a few important slides in a PowerPoint file.

Using Spire.Presentation, you can create a new presentation, copy the required slides from the original PowerPoint file, and then export them to OFD format.

Single Slide to OFD Conversion Workflow

  • Load the source PowerPoint file.
  • Create a new Presentation object.
  • Copy the required slides from the original presentation to the new presentation.
  • Save the new presentation as an OFD file.
  • Dispose of the Presentation objects to release resources.

Note: In Spire.Presentation, slide indexing starts from 0, so index 4 refers to the fifth slide in the presentation.

Sample Code:

#include "Spire.Presentation.o.h"

using namespace Spire::Presentation;
using namespace std;

int main()
{
    // Specify input and output paths
    wstring inputFile = L"Input.pptx";
    wstring outputFile = L"SingleSlide.ofd";

    // Load the source presentation
    intrusive_ptr<Presentation> presentation = new Presentation();
    presentation->LoadFromFile(inputFile.c_str());

    // Create a new presentation
    intrusive_ptr<Presentation> newPresentation = new Presentation();

    // Get the specific slide (for example: slide 5)
    intrusive_ptr<ISlide> slide = presentation->GetSlides()->GetItem(4);

    // Add the slide to the new presentation
    newPresentation->GetSlides()->Append(slide);

    // Save the slide as OFD
    newPresentation->SaveToFile(outputFile.c_str(), FileFormat::OFD);

    // Release resources
    presentation->Dispose();
    newPresentation->Dispose();

    return 0;
}

RESULT:

result of using spire presentation to convert a specific slide to ofd format

FAQs

1. Can I export PowerPoint files directly to OFD format with Microsoft PowerPoint?

No. Microsoft PowerPoint does not provide built-in support for exporting presentations to OFD format. Developers usually rely on document processing libraries or third-party tools to perform this conversion programmatically.

2. Why convert PowerPoint to OFD instead of PDF?

While PDF is widely used, some government and industry platforms specifically require OFD because it is a national standard document format designed for secure and long-term document storage.

3. Does Spire.Presentation require Microsoft Office?

No. Spire.Presentation for C++ is a standalone library that does not require Microsoft PowerPoint to be installed.

4. Can I convert multiple PowerPoint files to OFD at once?

Yes. By looping through multiple files in a directory and applying the same conversion method, you can easily build a batch conversion tool in C++ with Spire.Presentation.

Wrap-Up

In this tutorial, we showed how to perform PowerPoint to OFD conversion in C++ using Spire.Presentation for C++. With just a few lines of code, developers can load PPT or PPTX files and export them to OFD while preserving the original layout.

We also covered scenarios such as converting an entire presentation, exporting a single slide, and performing batch PPT to OFD conversion, making it easier to integrate this feature into automated workflows or enterprise systems. Download Spire.Presentation for C++ to try these examples and start converting PowerPoint files to OFD in your C++ applications.

Como curvar texto em documentos do Word

Curvar texto é uma maneira poderosa de melhorar o apelo visual de seus documentos, seja para criar um selo de empresa profissional, um logotipo criativo ou um certificado oficial. Muitos usuários procuram por como curvar texto no Word porque a opção não é apresentada diretamente nas configurações de fonte padrão. Neste guia, exploraremos técnicas manuais para criar texto curvado no Word e forneceremos uma solução programática para desenvolvedores que usam Python.

Usando WordArt para curvar texto no Word

O método mais tradicional envolve o uso da galeria WordArt no Microsoft Word. Esta ferramenta trata seu texto como um objeto gráfico, permitindo distorções geométricas complexas que o texto de parágrafo padrão não pode suportar. Se você está procurando como curvar palavras em documentos do Word com efeitos estilizados como sombras ou gradientes, este é o melhor ponto de partida.

Passo 1: Vá para a guia Inserir, clique no botão WordArt e selecione um estilo que se ajuste ao seu design.

Passo 2: Digite o conteúdo que deseja curvar na caixa de espaço reservado que aparece.

Passo 3: Com o objeto WordArt selecionado, navegue até a guia Formato da Forma, clique em Efeitos de Texto, passe o mouse sobre Transformar e escolha uma opção na seção Seguir Caminho.

Como curvar texto no Word usando WordArt

Passo 4: Arraste o pequeno círculo amarelo (alça de controle) na borda da caixa de texto para aumentar ou diminuir a intensidade da curva.

O resultado do texto curvado

Como curvar texto no Word 365

O Microsoft Word 365 usa o mesmo motor de transformação do WordArt que as versões de desktop modernas do Word, o que significa que os passos para criar texto curvado são quase idênticos.

Passo 1: Vá para a guia Inserir e selecione WordArt.

Passo 2: Digite seu texto dentro da caixa do WordArt.

Passo 3: Abra a guia Formato da Forma (ou Formato de Desenho).

Passo 4: Clique em Efeitos de Texto → Transformar → Seguir Caminho, e então escolha um estilo de arco como Arco para Cima ou Círculo.

O Word 365 também oferece várias predefinições de transformação adicionais, permitindo que você crie efeitos de texto curvado mais avançados em comparação com versões mais antigas do Microsoft Word.

Como curvar texto no Word usando uma caixa de texto

Se você prefere um visual mais limpo e minimalista sem os estilos predefinidos do WordArt, usar uma caixa de texto padrão é uma alternativa inteligente. Este método é ideal quando você precisa curvar palavras em arquivos do Word, mantendo uma estética profissional e simples. Ele também permite que você curve texto em layouts do Word sem se preocupar com preenchimentos de texto complexos.

Passo 1: Vá para a guia Inserir, clique em Caixa de Texto e selecione Caixa de Texto Simples para colocá-la em seu documento.

Passo 2: Clique com o botão direito na borda da caixa de texto, selecione Formatar Forma e defina tanto Preenchimento quanto Linha como "Sem preenchimento" e "Sem linha" para tornar o contêiner invisível.

Como curvar texto no Word usando caixa de texto

Passo 3: Selecione a caixa de texto, vá para a guia Formato da Forma, clique em Efeitos de Texto e escolha o estilo de arco desejado em Transformar.

Curvar texto em documentos do Word inserindo uma caixa de texto

Nota: Embora o uso de caixas de texto ofereça grande flexibilidade para curvar texto em documentos do Word, gerenciar múltiplos objetos flutuantes pode, às vezes, poluir seu layout. Se você precisar limpar seu documento mais tarde, confira nosso guia sobre como excluir caixas de texto no Word manualmente ou via código.

Ajustando seu texto curvado no Microsoft Word

Depois de aplicar a transformação básica, você pode achar que o alinhamento não está perfeito. Ajustar a aparência do texto curvado no Microsoft Word requer um entendimento básico de como o Word lida com as caixas delimitadoras de objetos.

Para garantir que seu texto no Word se curve exatamente como você imaginou, preste atenção à proporção da caixa de texto. Esticar a caixa horizontalmente achatará o arco, enquanto estreitá-la acentuará a curva. Você também pode usar a alça de "Girar" na parte superior da caixa para posicionar o arco em um ângulo específico, o que é particularmente útil para selos circulares onde o texto precisa envolver a parte inferior.

Para aprimorar ainda mais a segurança e a marca do seu documento, você também pode querer aprender como adicionar marcas d'água no Word para proteger seus designs criativos.

Criar texto curvado programaticamente no Word usando o Free Spire.Doc

Para desenvolvedores que precisam automatizar a geração de documentos, o clique manual não é eficiente o suficiente para a geração de documentos em grande escala. Você pode criar texto curvado programaticamente em documentos do Word usando a biblioteca Free Spire.Doc, que fornece controle profundo sobre objetos Shape e atributos WordArt.

O uso de código é altamente eficiente para fluxos de trabalho automatizados, garantindo que cada elemento de texto curvado mantenha alinhamento e estilo perfeitos em todos os seus arquivos gerados.

O trecho de código a seguir demonstra como usar o Free Spire.Doc for Python para criar um documento do Word e adicionar programaticamente uma forma de texto com efeito curvado.

from spire.doc import *
from spire.doc.common import *

# Crie um novo documento do Word
doc = Document()

# Adicione uma seção
section = doc.AddSection()

# Adicione um parágrafo
para = section.AddParagraph()

# Adicione uma forma e defina seu tamanho e tipo como TextCurve
# Parâmetros: Largura, Altura, ShapeType
shape = para.AppendShape(200, 100, ShapeType.TextCurve)

# Defina a posição vertical e horizontal da forma na página
shape.VerticalPosition = 50
shape.HorizontalPosition = 50

# Defina o conteúdo do WordArt
shape.WordArt.Text = "Texto Curvado Automatizado"

# Defina a cor de preenchimento e a cor do traço
shape.FillColor = Color.get_AliceBlue()
shape.StrokeColor = Color.get_DarkBlue()

# Salve o documento no caminho especificado
doc.SaveToFile("/output/CurvedText.docx", FileFormat.Docx2016)
doc.Close()

Aqui está a pré-visualização do arquivo de saída:

Curvar texto em documentos do Word usando Python

Perguntas Frequentes

P1: Posso curvar um parágrafo existente diretamente?

Não, o Microsoft Word exige que o texto esteja dentro de um contêiner Shape ou WordArt. Para fazer o texto curvar no Word, você precisa copiar o texto existente e colá-lo em um objeto WordArt ou em uma caixa de texto transformada.

P2: A curva permanecerá se eu exportar para PDF?

Sim, desde que você use uma ferramenta de conversão de alta qualidade como o Free Spire.Doc, o texto curvado será renderizado como um objeto vetorial ao ser convertido para PDF, garantindo que permaneça nítido e profissional.

Conclusão

Dominar como curvar texto no Word permite que você vá além da edição básica de documentos para o reino do design de layout profissional. Quer você escolha os métodos intuitivos da interface do usuário ou a automação robusta fornecida pelo Spire.Doc, criar texto dinâmico e não linear é essencial para a documentação moderna. Incentivamos você a baixar a versão de avaliação do Spire.Doc para experimentar esses recursos avançados de formatação em seus próprios projetos hoje.


Explore mais dicas de automação do Word:

Word 문서에서 텍스트를 구부리는 방법

텍스트를 구부리는 것은 전문적인 회사 직인, 창의적인 로고 또는 공식 인증서를 디자인하든 문서의 시각적 매력을 향상시키는 강력한 방법입니다. 많은 사용자가 Word에서 텍스트를 구부리는 방법을 검색하는데, 그 이유는 이 옵션이 표준 글꼴 설정에 직접 표시되지 않기 때문입니다. 이 가이드에서는 Word에서 구부러진 텍스트를 만드는 수동 기술을 살펴보고 Python을 사용하는 개발자를 위한 프로그래밍 방식 솔루션을 제공합니다.

WordArt를 사용하여 Word에서 텍스트 구부리기

가장 전통적인 방법은 Microsoft Word의 WordArt 갤러리를 사용하는 것입니다. 이 도구는 텍스트를 그래픽 개체로 취급하여 표준 단락 텍스트가 지원할 수 없는 복잡한 기하학적 왜곡을 허용합니다. 그림자나 그라데이션과 같은 스타일화된 효과로 Word 문서에서 단어를 구부리는 방법을 찾고 있다면 이것이 가장 좋은 출발점입니다.

1단계: 삽입 탭으로 이동하여 WordArt 버튼을 클릭하고 디자인에 맞는 스타일을 선택합니다.

2단계: 나타나는 자리 표시자 상자에 구부리고자 하는 내용을 입력합니다.

3단계: WordArt 개체를 선택한 상태에서 도형 서식 탭으로 이동하여 텍스트 효과를 클릭하고 변환 위로 마우스를 가져간 다음 경로 따르기 섹션에서 옵션을 선택합니다.

WordArt를 사용하여 Word에서 텍스트를 구부리는 방법

4단계: 텍스트 상자 테두리에 있는 작은 노란색 원(조정 핸들)을 드래그하여 곡선의 강도를 높이거나 낮춥니다.

구부러진 텍스트 결과

Word 365에서 텍스트를 구부리는 방법

Microsoft Word 365는 최신 데스크톱 버전의 Word와 동일한 WordArt 변환 엔진을 사용하므로 구부러진 텍스트를 만드는 단계가 거의 동일합니다.

1단계: 삽입 탭으로 이동하여 WordArt를 선택합니다.

2단계: WordArt 상자 안에 텍스트를 입력합니다.

3단계: 도형 서식(또는 그리기 서식) 탭을 엽니다.

4단계: 텍스트 효과 → 변환 → 경로 따르기를 클릭한 다음 위로 휘기 또는 과 같은 호 스타일을 선택합니다.

Word 365는 또한 여러 추가 변환 사전 설정을 제공하여 이전 버전의 Microsoft Word에 비해 더 고급스러운 구부러진 텍스트 효과를 만들 수 있습니다.

텍스트 상자를 사용하여 Word에서 텍스트를 구부리는 방법

WordArt의 미리 정의된 스타일 없이 더 깨끗하고 미니멀한 모양을 선호한다면 표준 텍스트 상자를 사용하는 것이 현명한 대안입니다. 이 방법은 전문적이고 단순한 미학을 유지하면서 Word 파일에서 단어를 구부려야 할 때 이상적입니다. 또한 복잡한 텍스트 채우기에 대해 걱정하지 않고 Word 레이아웃에서 텍스트를 구부릴 수 있습니다.

1단계: 삽입 탭으로 이동하여 텍스트 상자를 클릭하고 단순 텍스트 상자를 선택하여 문서에 배치합니다.

2단계: 텍스트 상자 가장자리를 마우스 오른쪽 버튼으로 클릭하고 도형 서식을 선택한 다음 채우기을 모두 "채우기 없음" 및 "선 없음"으로 설정하여 컨테이너를 보이지 않게 만듭니다.

텍스트 상자를 사용하여 Word에서 텍스트를 구부리는 방법

3단계: 텍스트 상자를 선택하고 도형 서식 탭으로 이동하여 텍스트 효과를 클릭하고 변환에서 원하는 호 스타일을 선택합니다.

텍스트 상자를 삽입하여 Word 문서에서 텍스트 구부리기

참고: 텍스트 상자를 사용하면 Word 문서에서 텍스트를 구부리는 데 큰 유연성을 제공하지만 여러 개의 부동 개체를 관리하면 레이아웃이 복잡해질 수 있습니다. 나중에 문서를 정리해야 하는 경우 수동으로 또는 코드를 통해 Word에서 텍스트 상자를 삭제하는 방법에 대한 가이드를 확인하십시오.

Microsoft Word에서 구부러진 텍스트 미세 조정

기본 변환을 적용한 후 정렬이 완벽하지 않다는 것을 알 수 있습니다. Microsoft Word에서 구부러진 텍스트의 모양을 미세 조정하려면 Word가 개체 경계 상자를 처리하는 방법에 대한 기본 이해가 필요합니다.

Word의 텍스트가 상상한 대로 정확하게 구부러지도록 하려면 텍스트 상자의 종횡비에 주의하십시오. 상자를 가로로 늘리면 호가 평평해지고 좁히면 곡선이 더 날카로워집니다. 상자 상단의 "회전" 핸들을 사용하여 특정 각도로 호를 배치할 수도 있으며, 이는 텍스트가 아래쪽을 감싸야 하는 원형 스탬프에 특히 유용합니다.

문서의 보안과 브랜딩을 더욱 강화하려면 창의적인 디자인을 보호하기 위해 Word에 워터마크를 추가하는 방법을 배우고 싶을 수도 있습니다.

Free Spire.Doc을 사용하여 프로그래밍 방식으로 Word에서 구부러진 텍스트 만들기

문서 생성을 자동화해야 하는 개발자에게는 수동 클릭이 대규모 문서 생성에 충분히 효율적이지 않습니다. Shape 개체 및 WordArt 특성에 대한 심층적인 제어를 제공하는 Free Spire.Doc 라이브러리를 사용하여 프로그래밍 방식으로 Word 문서에서 구부러진 텍스트를 만들 수 있습니다.

코드를 사용하는 것은 자동화된 워크플로에 매우 효율적이어서 생성된 모든 파일에서 모든 구부러진 텍스트 요소가 완벽한 정렬과 스타일을 유지하도록 보장합니다.

다음 코드 조각은 Python용 Free Spire.Doc을 사용하여 Word 문서를 만들고 구부러진 효과가 있는 텍스트 도형을 프로그래밍 방식으로 추가하는 방법을 보여줍니다.

from spire.doc import *
from spire.doc.common import *

# Create a new Word document
doc = Document()

# Add a section
section = doc.AddSection()

# Add a paragraph
para = section.AddParagraph()

# Add a shape and set its size and type to TextCurve
# Parameters: Width, Height, ShapeType
shape = para.AppendShape(200, 100, ShapeType.TextCurve)

# Set the vertical and horizontal position of the shape on the page
shape.VerticalPosition = 50
shape.HorizontalPosition = 50

# Set the content of the WordArt
shape.WordArt.Text = "자동화된 구부러진 텍스트"

# Set the fill color and stroke color
shape.FillColor = Color.get_AliceBlue()
shape.StrokeColor = Color.get_DarkBlue()

# Save the document to the specified path
doc.SaveToFile("/output/CurvedText.docx", FileFormat.Docx2016)
doc.Close()

다음은 출력 파일의 미리보기입니다.

Python을 사용하여 Word 문서에서 텍스트 구부리기

자주 묻는 질문

Q1: 기존 단락을 직접 구부릴 수 있나요?

아니요, Microsoft Word에서는 텍스트가 Shape 또는 WordArt 컨테이너 내에 있어야 합니다. Word에서 텍스트를 구부리려면 기존 텍스트를 복사하여 WordArt 개체나 변형된 텍스트 상자에 붙여넣어야 합니다.

Q2: PDF로 내보내도 곡선이 유지되나요?

예, Free Spire.Doc과 같은 고품질 변환 도구를 사용하는 한 구부러진 텍스트는 PDF로 변환될 때 벡터 개체로 렌더링되어 선명하고 전문적으로 유지됩니다.

결론

Word에서 텍스트를 구부리는 방법을 마스터하면 기본 문서 편집을 넘어 전문적인 레이아웃 디자인 영역으로 이동할 수 있습니다. 직관적인 UI 방법을 선택하든 Spire.Doc에서 제공하는 강력한 자동화를 선택하든 동적 비선형 텍스트를 만드는 것은 최신 문서화에 필수적입니다. 오늘 자신의 프로젝트에서 이러한 고급 서식 기능을 실험해 보려면 Spire.Doc 평가판을 다운로드하는 것이 좋습니다.


더 많은 Word 자동화 팁 살펴보기:

Come Curvare il Testo nei Documenti di Word

Curvare il testo è un modo potente per migliorare l'aspetto visivo dei tuoi documenti, che tu stia progettando un sigillo aziendale professionale, un logo creativo o un certificato ufficiale. Molti utenti cercano come curvare il testo in Word perché l'opzione non è presentata direttamente nelle impostazioni standard dei caratteri. In questa guida, esploreremo le tecniche manuali per creare testo curvato in Word e forniremo una soluzione programmatica per gli sviluppatori che usano Python.

Usare WordArt per Curvare il Testo in Word

Il metodo più tradizionale prevede l'uso della galleria WordArt in Microsoft Word. Questo strumento tratta il tuo testo come un oggetto grafico, consentendo distorsioni geometriche complesse che il testo di un paragrafo standard non può supportare. Se stai cercando come curvare le parole nei documenti di Word con effetti stilizzati come ombre o sfumature, questo è il punto di partenza migliore.

Passaggio 1: Vai alla scheda Inserisci, fai clic sul pulsante WordArt e seleziona uno stile che si adatti al tuo design.

Passaggio 2: Digita il contenuto che desideri curvare nella casella segnaposto che appare.

Passaggio 3: Con l'oggetto WordArt selezionato, vai alla scheda Formato forma, fai clic su Effetti testo, passa il mouse su Trasformazione e scegli un'opzione nella sezione Segui percorso.

Come Curvare il Testo in Word Usando WordArt

Passaggio 4: Trascina il piccolo cerchio giallo (maniglia di controllo) sul bordo della casella di testo per aumentare o diminuire l'intensità della curva.

Il Risultato del Testo Curvato

Come Curvare il Testo in Word 365

Microsoft Word 365 utilizza lo stesso motore di trasformazione WordArt delle versioni desktop moderne di Word, il che significa che i passaggi per creare testo curvato sono quasi identici.

Passaggio 1: Vai alla scheda Inserisci e seleziona WordArt.

Passaggio 2: Digita il tuo testo all'interno della casella WordArt.

Passaggio 3: Apri la scheda Formato forma (o Formato disegno).

Passaggio 4: Fai clic su Effetti testo → Trasformazione → Segui percorso, quindi scegli uno stile di arco come Arco verso l'alto o Cerchio.

Word 365 offre anche diverse preimpostazioni di trasformazione aggiuntive, che consentono di creare effetti di testo curvato più avanzati rispetto alle versioni precedenti di Microsoft Word.

Come Curvare il Testo in Word Usando una Casella di Testo

Se preferisci un aspetto più pulito e minimalista senza gli stili predefiniti di WordArt, usare una casella di testo standard è un'alternativa intelligente. Questo metodo è ideale quando hai bisogno di curvare le parole nei file di Word mantenendo un'estetica professionale e semplice. Ti permette anche di curvare il testo nei layout di Word senza preoccuparti di riempimenti di testo complessi.

Passaggio 1: Vai alla scheda Inserisci, fai clic su Casella di testo e seleziona Casella di testo semplice per inserirla nel tuo documento.

Passaggio 2: Fai clic con il pulsante destro del mouse sul bordo della casella di testo, seleziona Formato forma e imposta sia Riempimento che Linea su "Nessun riempimento" e "Nessuna linea" per rendere il contenitore invisibile.

Come Curvare il Testo in Word Usando una Casella di Testo

Passaggio 3: Seleziona la casella di testo, vai alla scheda Formato forma, fai clic su Effetti testo e scegli lo stile di arco desiderato in Trasformazione.

Curvare il Testo nei Documenti di Word Inserendo una Casella di Testo

Nota: sebbene l'uso delle caselle di testo offra una grande flessibilità per curvare il testo nei documenti di Word, la gestione di più oggetti mobili può talvolta ingombrare il layout. Se in seguito avrai bisogno di ripulire il tuo documento, consulta la nostra guida su come eliminare le caselle di testo in Word manualmente o tramite codice.

Affinare il Testo Curvato in Microsoft Word

Una volta applicata la trasformazione di base, potresti scoprire che l'allineamento non è perfetto. Per affinare l'aspetto del testo curvato in Microsoft Word è necessaria una conoscenza di base di come Word gestisce i riquadri di delimitazione degli oggetti.

Per assicurarti che il tuo testo in Word si curvi esattamente come hai immaginato, presta attenzione al rapporto d'aspetto della casella di testo. Allungando la casella orizzontalmente si appiattirà l'arco, mentre restringendola si accentuerà la curva. Puoi anche usare la maniglia "Ruota" nella parte superiore della casella per posizionare l'arco ad un angolo specifico, il che è particolarmente utile per i timbri circolari in cui il testo deve avvolgere la parte inferiore.

Per migliorare ulteriormente la sicurezza e il branding del tuo documento, potresti anche voler imparare come aggiungere filigrane in Word per proteggere i tuoi design creativi.

Creare Programmaticamente Testo Curvato in Word usando Free Spire.Doc

Per gli sviluppatori che necessitano di automatizzare la generazione di documenti, il clic manuale non è abbastanza efficiente per la generazione di documenti su larga scala. È possibile creare programmaticamente testo curvato nei documenti di Word utilizzando la libreria Free Spire.Doc, che fornisce un controllo approfondito sugli oggetti Shape e sugli attributi di WordArt.

L'uso del codice è altamente efficiente per i flussi di lavoro automatizzati, garantendo che ogni elemento di testo curvato mantenga un allineamento e uno stile perfetti in tutti i file generati.

Il seguente frammento di codice dimostra come utilizzare Free Spire.Doc for Python per creare un documento Word e aggiungere programmaticamente una forma di testo con un effetto curvo.

from spire.doc import *
from spire.doc.common import *

# Create a new Word document
doc = Document()

# Add a section
section = doc.AddSection()

# Add a paragraph
para = section.AddParagraph()

# Add a shape and set its size and type to TextCurve
# Parameters: Width, Height, ShapeType
shape = para.AppendShape(200, 100, ShapeType.TextCurve)

# Set the vertical and horizontal position of the shape on the page
shape.VerticalPosition = 50
shape.HorizontalPosition = 50

# Set the content of the WordArt
shape.WordArt.Text = "Automated Curved Text"

# Set the fill color and stroke color
shape.FillColor = Color.get_AliceBlue()
shape.StrokeColor = Color.get_DarkBlue()

# Save the document to the specified path
doc.SaveToFile("/output/CurvedText.docx", FileFormat.Docx2016)
doc.Close()

Ecco l'anteprima del file di output:

Curvare il Testo nei Documenti di Word Usando Python

Domande Frequenti

D1: Posso curvare direttamente un paragrafo esistente?

No, Microsoft Word richiede che il testo si trovi all'interno di un contenitore Shape o WordArt. Per far curvare il testo in Word, è necessario copiare il testo esistente e incollarlo in un oggetto WordArt o in una casella di testo trasformata.

D2: La curva rimarrà se esporto in PDF?

Sì, a condizione che si utilizzi uno strumento di conversione di alta qualità come Free Spire.Doc, il testo curvato verrà reso come un oggetto vettoriale durante la conversione in PDF, garantendo che rimanga nitido e professionale.

Conclusione

Padroneggiare come curvare il testo in Word ti consente di andare oltre la semplice modifica di documenti per entrare nel regno del design di layout professionale. Sia che tu scelga i metodi intuitivi dell'interfaccia utente o la robusta automazione fornita da Spire.Doc, la creazione di testo dinamico e non lineare è essenziale per la documentazione moderna. Ti incoraggiamo a scaricare la versione di prova di Spire.Doc per sperimentare oggi stesso queste funzionalità di formattazione avanzate nei tuoi progetti.


Esplora Altri Suggerimenti per l'Automazione di Word: