Chuyển đổi dữ liệu JSON thành bảng tính Excel là một nhu cầu thường gặp khi báo cáo hoặc phân tích thông tin có cấu trúc. Aspose.Words Cloud SDK for Java cung cấp một API mạnh mẽ dựa trên đám mây, giúp đơn giản hoá quá trình chuyển đổi này trong các ứng dụng Java. Trong hướng dẫn này, chúng tôi sẽ trình bày cách chuyển đổi JSON sang XLSX trong Java, bao gồm một ví dụ mã đầy đủ, các cuộc gọi REST tương đương bằng cURL, và các khuyến nghị thực tiễn quan trọng. Khi kết thúc, bạn sẽ có thể tạo các tệp XLSX từ bất kỳ nguồn JSON nào và xử lý các cấu trúc lồng nhau một cách dễ dàng.

Tạo XLSX từ JSON bằng Java - Ví dụ mã đầy đủ

Ví dụ này minh họa cách đọc tệp JSON, tạo bảng DOCX và chuyển đổi nó sang XLSX bằng Aspose.Words Cloud SDK for Java.

import com.aspose.words.cloud.*;
import com.aspose.words.cloud.model.*;
import com.aspose.words.cloud.api.*;
import com.aspose.words.cloud.auth.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;
import java.util.*;

public class JsonToXlsxConverter {
    public static void main(String[] args) throws Exception {
        // Initialize API
        String clientId = "YOUR_CLIENT_ID";
        String clientSecret = "YOUR_CLIENT_SECRET";
        WordsApi wordsApi = new WordsApi(clientId, clientSecret);
        
        // Paths
        String jsonPath = "data.json";
        String tempDocxPath = "temp.docx";
        String outputXlsxPath = "output.xlsx";
        
        // Read JSON
        ObjectMapper mapper = new ObjectMapper();
        List<Map<String, Object>> records = mapper.readValue(new File(jsonPath),
                mapper.getTypeFactory().constructCollectionType(List.class, Map.class));
        
        // Define column order (keys from first record)
        List<String> columns = new ArrayList<>(records.get(0).keySet());
        
        // Create empty DOCX in cloud
        CreateDocumentRequest createRequest = new CreateDocumentRequest("temp.docx");
        wordsApi.createDocument(createRequest);
        
        // Build table rows
        TableRowInsert requestRow = new TableRowInsert();
        // First row - header
        TableRow headerRow = new TableRow();
        List<TableCell> headerCells = new ArrayList<>();
        for (String col : columns) {
            TableCell cell = new TableCell();
            cell.setText(col);
            headerCells.add(cell);
        }
        headerRow.setTableCellList(headerCells);
        // Insert header row at position 0
        InsertTableRowRequest insertHeader = new InsertTableRowRequest("temp.docx", 0, headerRow);
        wordsApi.insertTableRow(insertHeader);
        
        // Insert data rows
        int rowIndex = 1;
        for (Map<String, Object> rec : records) {
            TableRow dataRow = new TableRow();
            List<TableCell> dataCells = new ArrayList<>();
            for (String col : columns) {
                TableCell cell = new TableCell();
                cell.setText(String.valueOf(rec.get(col)));
                dataCells.add(cell);
            }
            dataRow.setTableCellList(dataCells);
            InsertTableRowRequest insertRow = new InsertTableRowRequest("temp.docx", rowIndex, dataRow);
            wordsApi.insertTableRow(insertRow);
            rowIndex++;
        }
        
        // Convert DOCX to XLSX
        ConvertDocumentRequest convertRequest = new ConvertDocumentRequest("temp.docx", "xlsx");
        byte[] xlsxBytes = wordsApi.convertDocument(convertRequest);
        try (FileOutputStream fos = new FileOutputStream(outputXlsxPath)) {
            fos.write(xlsxBytes);
        }
    }
}

Lưu ý: Ví dụ mã này minh họa chức năng cốt lõi. Trước khi sử dụng trong dự án của bạn, hãy chắc chắn cập nhật mọi đường dẫn tệp và giá trị cấu hình để phù hợp với môi trường thực tế của bạn, xác minh rằng tất cả các phụ thuộc cần thiết đã được cài đặt đúng cách, và kiểm tra kỹ lưỡng trong môi trường phát triển. Nếu bạn gặp bất kỳ vấn đề nào, vui lòng tham khảo tài liệu chính thức hoặc liên hệ với đội hỗ trợ để được trợ giúp.

Chuyển đổi JSON sang XLSX qua REST API bằng cURL

Việc chuyển đổi tương tự có thể được thực hiện mà không cần viết mã Java bằng cách gọi trực tiếp Aspose.Words Cloud REST API.

  1. Lấy token truy cập - API sử dụng OAuth 2.0.
curl -X POST "https://api.aspose.cloud/connect/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
  1. Tải lên tệp JSON (API yêu cầu nguồn DOCX, vì vậy chúng ta sẽ tải lên một tệp DOCX tạm thời).
curl -X PUT "https://api.aspose.cloud/v4.0/words/temp.docx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document" \
     --data-binary "@temp.docx"
  1. Tạo bảng từ JSON - bước này được SDK xử lý trong mã; với REST API bạn sẽ tải lên một DOCX đã được điền sẵn chứa bảng.

  2. Chuyển đổi DOCX sang XLSX.

curl -X GET "https://api.aspose.cloud/v4.0/words/temp.docx?format=xlsx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -o output.xlsx

Để xem danh sách đầy đủ các tham số, hãy xem tài liệu API chính thức.

Chuyển đổi JSON sang XLSX trong Java - Cách hoạt động của mã

Dưới đây là bản tóm tắt ngắn gọn các phần chính trong ví dụ Java.

  1. Khởi tạo API - WordsApi wordsApi = new WordsApi(clientId, clientSecret); tạo một client đã xác thực.
WordsApi wordsApi = new WordsApi(clientId, clientSecret);
  1. Đọc JSON - ObjectMapper giải mã tệp JSON thành một danh sách các map, bảo tồn thứ tự trường gốc.
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> records = mapper.readValue(
        new File(jsonPath),
        mapper.getTypeFactory().constructCollectionType(List.class, Map.class));
  1. Tạo một DOCX trong đám mây - CreateDocumentRequest tạo một DOCX trống sẽ chứa bảng.
CreateDocumentRequest createRequest = new CreateDocumentRequest("temp.docx");
wordsApi.createDocument(createRequest);
  1. Xây dựng hàng tiêu đề - Các khóa của bản ghi đầu tiên xác định thứ tự cột, và mỗi khóa trở thành một ô tiêu đề.
TableRow headerRow = new TableRow();
List<TableCell> headerCells = new ArrayList<>();
for (String col : columns) {
    TableCell cell = new TableCell();
    cell.setText(col);
    headerCells.add(cell);
}
headerRow.setTableCellList(headerCells);
InsertTableRowRequest insertHeader = new InsertTableRowRequest("temp.docx", 0, headerRow);
wordsApi.insertTableRow(insertHeader);
  1. Chèn các hàng dữ liệu - Mỗi đối tượng JSON được chuyển thành một TableRow trong đó mỗi cell nhận biểu diễn dạng chuỗi của giá trị tương ứng.
for (Map<String, Object> rec : records) {
    TableRow dataRow = new TableRow();
    List<TableCell> dataCells = new ArrayList<>();
    for (String col : columns) {
        TableCell cell = new TableCell();
        cell.setText(String.valueOf(rec.get(col)));
        dataCells.add(cell);
    }
    dataRow.setTableCellList(dataCells);
    InsertTableRowRequest insertRow = new InsertTableRowRequest("temp.docx", rowIndex, dataRow);
    wordsApi.insertTableRow(insertRow);
    rowIndex++;
}
  1. Chuyển đổi sang XLSX - ConvertDocumentRequest cho biết dịch vụ sẽ chuyển đổi tệp DOCX tạm thời thành tệp XLSX, sau đó được ghi cục bộ.
ConvertDocumentRequest convertRequest = new ConvertDocumentRequest("temp.docx", "xlsx");
byte[] xlsxBytes = wordsApi.convertDocument(convertRequest);

Để tham khảo chi tiết API, hãy truy cập Aspose.Words Cloud API Reference.

Cài đặt và cấu hình Aspose.Words Cloud SDK for Java

Thêm phụ thuộc Maven vào pom.xml của dự án của bạn:

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words-cloud</artifactId>
    <version>26.9.0</version>
</dependency>

Tải xuống các JAR mới nhất từ trang tải xuống nếu bạn muốn cài đặt thủ công.
Yêu cầu trước:

  • Java 8 hoặc cao hơn.
  • Một tài khoản Aspose Cloud với client ID và client secret.
  • Truy cập mạng tới api.aspose.cloud.

Cấu hình SDK bằng cách đặt các biến clientIdclientSecret như được hiển thị trong ví dụ mã.

Kết luận

Việc chuyển đổi JSON sang XLSX trong Java trở nên đơn giản với Aspose.Words Cloud SDK for Java. Ví dụ được cung cấp hướng dẫn bạn cách đọc JSON, tạo bảng DOCX và chuyển đổi nó thành sổ làm việc XLSX, trong khi phần cURL hiển thị một giải pháp không phụ thuộc ngôn ngữ. Hãy nhớ đảm bảo có giấy phép phù hợp cho việc sử dụng trong môi trường sản xuất; bạn có thể xem giá trên trang sản phẩm và nhận giấy phép tạm thời từ trang giấy phép tạm thời. Với những công cụ này, bạn có thể tự động tạo báo cáo Excel từ bất kỳ nguồn JSON nào một cách nhanh chóng và đáng tin cậy.

Câu hỏi thường gặp

Làm thế nào để chuyển đổi JSON sang XLSX trong Java bằng Aspose.Words Cloud SDK for Java?
Sử dụng mẫu mã ở trên hoặc REST API. SDK đọc JSON, tạo một bảng DOCX, sau đó chuyển đổi nó sang XLSX bằng một cuộc gọi API duy nhất.

SDK có thể xử lý cấu trúc JSON lồng nhau không?
Có. Làm phẳng các đối tượng lồng nhau thành các cột riêng biệt trước khi chèn hàng, như đã được minh họa trong phần “Practical Tips”.

Có cần giấy phép cho việc triển khai sản xuất không?
Một giấy phép hợp lệ là bắt buộc cho môi trường sản xuất. Các tùy chọn mua được liệt kê trên trang sản phẩm, và một giấy phép tạm thời có sẵn để thử nghiệm tại trang giấy phép tạm thời.

Có cách nào thực hiện chuyển đổi mà không cần viết mã Java không?
Chắc chắn. Ví dụ cURL cho thấy cách đạt được kết quả tương tự thông qua REST API, có thể được gọi từ bất kỳ nền tảng nào.

Đọc thêm