將資料從 JSON 檔案匯出至 Excel 試算表是現代 Node.JS 應用程式中常見的報告與資料交換需求。Aspose.OCR Cloud SDK for Node.js 提供強大的 API,能直接在雲端處理此轉換。在本指南中,您將學習如何在 Node.JS 中使用 async/await 模式以及 SDK 的 convertDocument 方法將 JSON 轉換為 XLSX。我們將逐步說明前置條件、詳細程式碼走查、完整範例,甚至提供 cURL 替代方案以整合 REST。

開始之前:先決條件與安裝

要遵循本教程,您需要:

  • 本機已安裝 Node.js 14 或更新版本。
  • 擁有已啟用 OCR API 的 Aspose Cloud 帳戶。
  • 從 Aspose Cloud 控制台取得的 Client IdClient Secret
  • 可存取 JSON 原始檔與 XLSX 輸出檔案的檔案系統。

使用 npm 安裝 SDK:

npm install aspose-ocr-cloud

從官方發行頁面下載最新套件:Aspose.OCR Cloud SDK for Node.js Download。安裝完成後,您即可開始編寫程式碼。

以下程式碼片段示範如何使用您的憑證設定 OCR 客戶端:

const { OcrApi, Configuration } = require('asposeocrcloud');

const config = new Configuration({
    clientId: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET'
});
const ocrApi = new OcrApi(config);

當客戶端準備就緒後,接下來的章節將一步一步演示轉換工作流程。

逐步指南:在 Node.JS 中將 JSON 轉換為 XLSX

以下是將 JSON 轉換為 XLSX 在 Node.JS 中所需的每個操作的詳細步驟說明。

步驟 1:載入來源文件

首先,為您想要轉換的 JSON 檔案建立讀取串流。

const fs = require('fs');
const path = require('path');

const inputJsonPath = path.resolve(__dirname, 'input.json');
const jsonFileStream = fs.createReadStream(inputJsonPath);

步驟 2:設定 OCR API 客戶端

重新使用先前顯示的配置來實例化 API 物件。

const { OcrApi, Configuration } = require('asposeocrcloud');

const config = new Configuration({
    clientId: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET'
});
const ocrApi = new OcrApi(config);

步驟 3:呼叫 ConvertDocument 方法

呼叫轉換端點,將目標格式指定為 xlsx

const response = await ocrApi.convertDocument({
    format: 'xlsx',
    file: jsonFileStream
});

SDK 會在 response.body 中返回二進位 XLSX 資料。

步驟 4:寫入 XLSX 輸出檔案

將二進位資料持久化到磁碟上的檔案。

const outputXlsxPath = path.resolve(__dirname, 'output.xlsx');
fs.writeFileSync(outputXlsxPath, response.body, { encoding: 'binary' });
console.log('Conversion completed successfully:', outputXlsxPath);

第5步:清理資源

關閉檔案流以釋放系統資源。

jsonFileStream.close();

透過這些步驟,您已成功在 Node.JS 中使用 Aspose OCR Cloud library 執行將 JSON 轉換為 XLSX 的操作。

JSON 轉換為 XLSX(Node.JS)- 完整程式碼範例

以下範例示範了在 Node.JS 中使用 Aspose.OCR Cloud SDK 將 JSON 轉換為 XLSX 的完整實作。

const fs = require('fs');
const path = require('path');
const { OcrApi, Configuration } = require('asposeocrcloud');

(async () => {
    // Configure Aspose OCR Cloud client
    const config = new Configuration({
        clientId: 'YOUR_CLIENT_ID',
        clientSecret: 'YOUR_CLIENT_SECRET'
    });
    const ocrApi = new OcrApi(config);

// Define input JSON and output XLSX paths
    const inputJsonPath = path.resolve(__dirname, 'input.json');
    const outputXlsxPath = path.resolve(__dirname, 'output.xlsx');

// Prepare file stream for the JSON file
    const jsonFileStream = fs.createReadStream(inputJsonPath);

try {
        // Convert JSON to XLSX using Aspose OCR Cloud SDK
        const response = await ocrApi.convertDocument({
            format: 'xlsx',
            file: jsonFileStream
        });

// Write the returned binary data to the XLSX file
        fs.writeFileSync(outputXlsxPath, response.body, { encoding: 'binary' });

console.log('Conversion completed successfully:', outputXlsxPath);
    } catch (error) {
        console.error('Conversion failed:', error);
    } finally {
        // Ensure the file stream is closed
        jsonFileStream.close();
    }
})();

注意: 此程式碼範例示範了核心功能。在將其用於您的專案之前,請確保更新所有檔案路徑和設定值以符合實際環境,驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。若遇到任何問題,請參閱官方文件或聯繫支援團隊尋求協助。

cURL 方法將 JSON 轉換為 XLSX(Node.JS)

如果您偏好純粹的 REST 解決方案,則可以使用 cURL 命令執行相同的轉換。此方法同樣使用主要短語 convert JSON to XLSX in Node.JS

  1. 取得存取權杖
   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. 上傳 JSON 檔案並請求轉換
curl -X POST "https://api.aspose.cloud/v3.0/ocr/convert?format=xlsx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -F "file=@input.json"

回應包含二進位 XLSX 負載。

  1. 將 XLSX 輸出儲存到本機
curl -X GET "https://api.aspose.cloud/v3.0/ocr/convert/result/output.xlsx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -o output.xlsx

這些指令說明了如何在不編寫任何 Node.js 程式碼的情況下達成相同的結果。欲了解更多細節,請參閱 官方 API 文件

結論

在 Node.JS 中將 JSON 轉換為 XLSX 變得簡單,只要利用 Aspose.OCR Cloud SDK for Node.js。SDK 處理繁重的工作,讓您可以專注於業務邏輯,而不是檔案格式的細節。請務必保護您的客戶端憑證,優雅地處理錯誤,並使用實際資料大小進行測試。對於生產環境的部署,您需要付費訂閱;價格資訊可在產品頁面上查閱,且可從臨時許可頁面取得臨時許可。祝開發愉快!

常見問題

如何在 Node.JS 中使用 Aspose.OCR Cloud SDK 將 JSON 轉換為 XLSX?
使用 format: 'xlsx' 參數呼叫 OcrApi.convertDocument 方法。本文中的完整程式碼範例展示了具體的實作步驟。

OCR Cloud API 需要什麼驗證?
在 Aspose Cloud 儀表板中建立 client ID 和 client secret,然後將它們交換為 OAuth 令牌。SDK 的 Configuration 物件會自動管理令牌的取得。

我可以有效地處理大型 JSON 檔案嗎?
是的。SDK 會串流輸入檔案,保持低記憶體使用量。將此與 async/await 結合,可讓 Node.js 事件迴圈保持回應。

我可以在哪裡找到更多範例和支援?
訪問官方 GitHub 存儲庫、Aspose 文件站點,或在 支援論壇 提問。

Read More