從 Excel 活頁簿中提取原始文字是構建資料管道或生成簡單報告時的常見需求。如果您想了解 如何在 Python 中將 Excel 活頁簿轉換為文字,GroupDocs.Conversion Cloud SDK for Python 讓這變得簡單。本指南將帶您完成安裝 SDK、上傳活頁簿、配置轉換選項以及獲取純文字 TXT 結果的過程。完成後,您將擁有可重用的腳本以及一組用於 REST‑based 自動化的 cURL 命令。
開始之前:先決條件與安裝
在開始之前,請確保您具備以下條件:
- Python 3.7 或更新版本已安裝在您的機器上。
- 有效的 GroupDocs Cloud 帳戶(client ID 和 client secret)。
- 能夠訪問 GroupDocs Cloud 端點的網路連接。
使用 pip 安裝 SDK:
pip install groupdocs-conversion-cloud
您也可以從官方發布頁面下載最新的套件。安裝完成後,將您的憑證設置為環境變數,或稍後在程式碼中替換佔位符。SDK 準備就緒後,您即可開始轉換過程。
一步一步構建:如何在 Python 中將 Excel 工作簿轉換為文字
步驟 1:配置憑證
首先,建立一個 Configuration 物件並提供您的客戶端 ID 和密鑰。此物件用於所有後續的 API 呼叫。
import os
from groupdocs_conversion_cloud import Configuration
client_id = os.getenv("GROUPDOCS_CLIENT_ID", "YOUR_CLIENT_ID")
client_secret = os.getenv("GROUPDOCS_CLIENT_SECRET", "YOUR_CLIENT_SECRET")
config = Configuration()
config.client_id = client_id
config.client_secret = client_secret
Configuration 類別的文件位於 API 參考。
步驟 2:上傳 Excel 工作簿
將本機 Excel 檔案上傳至 GroupDocs Cloud storage。若您的檔案已在雲端,則此步驟為可選。
from groupdocs_conversion_cloud import ApiClient, UploadFileApi, UploadFileRequest
api_client = ApiClient(config)
upload_api = UploadFileApi(api_client)
local_excel_path = "sample.xlsx"
remote_excel_path = "sample.xlsx"
with open(local_excel_path, "rb") as f:
upload_request = UploadFileRequest(
path=remote_excel_path,
file=f.read()
)
upload_api.upload_file(upload_request)
UploadFileApi 處理檔案傳輸;有關更多詳細資訊,請參閱其文件。
第 3 步:定義轉換選項
建立一個 TxtConvertOptions 物件,以指定任何可選參數,例如頁面範圍。然後建立 ConvertSettings 物件,將所有內容結合在一起。
from groupdocs_conversion_cloud import (
FileInfo,
TxtConvertOptions,
ConvertSettings,
)
file_info = FileInfo()
file_info.file_path = remote_excel_path
txt_options = TxtConvertOptions()
# txt_options.page_number = 1 # Uncomment to start from a specific page
# txt_options.page_count = 1 # Uncomment to limit the number of pages
convert_settings = ConvertSettings()
convert_settings.file_info = file_info
convert_settings.format = "txt"
convert_settings.output_path = "sample.txt"
convert_settings.options = txt_options
TxtConvertOptions 類別讓您微調轉換;請參閱官方文件 以了解所有可用欄位。
步驟 4:執行轉換
呼叫 ConvertApi 的 convert 方法,使用已準備好的設定。回應中包含一個下載已轉換檔案的 URL。
from groupdocs_conversion_cloud import ConvertApi, ApiException
convert_api = ConvertApi(api_client)
try:
conversion_result = convert_api.convert(convert_settings)
print(f"Conversion succeeded. Download URL: {conversion_result.url}")
except ApiException as e:
print(f"Conversion failed: {e}")
如果呼叫成功,您將收到 TXT 檔案的直接下載連結。
步驟 5:檢索結果
使用前一步的 URL 下載純文字檔案到本機環境,或在應用程式中進一步處理它。
提示: 您可以使用簡單的
requests.get()呼叫自動化下載,透過與轉換請求相同的存取權杖處理驗證。
透過這些步驟,您現在已擁有一個完整的工作流程,用於 如何在 Python 中將 Excel 工作簿轉換為文字,使用 GroupDocs library。
Excel 工作簿文字轉換 - 完整程式碼範例
以下範例展示了從頭到尾的完整實作。
import os
from groupdocs_conversion_cloud import (
Configuration,
ApiClient,
UploadFileApi,
UploadFileRequest,
ConvertApi,
ConvertSettings,
FileInfo,
TxtConvertOptions,
ApiException,
)
def main():
# ----------------------------------------------------------------------
# 1. Configure credentials (replace placeholders or set env variables)
# ----------------------------------------------------------------------
client_id = os.getenv("GROUPDOCS_CLIENT_ID", "YOUR_CLIENT_ID")
client_secret = os.getenv("GROUPDOCS_CLIENT_SECRET", "YOUR_CLIENT_SECRET")
config = Configuration()
config.client_id = client_id
config.client_secret = client_secret
api_client = ApiClient(config)
# ----------------------------------------------------------------------
# 2. Upload local Excel workbook to GroupDocs Cloud storage (optional)
# ----------------------------------------------------------------------
local_excel_path = "sample.xlsx" # path to the Excel file on your machine
remote_excel_path = "sample.xlsx" # path where the file will be stored in the cloud
upload_api = UploadFileApi(api_client)
try:
with open(local_excel_path, "rb") as f:
upload_request = UploadFileRequest(
path=remote_excel_path,
file=f.read()
)
upload_api.upload_file(upload_request)
print(f"Uploaded '{local_excel_path}' to cloud storage as '{remote_excel_path}'.")
except (ApiException, IOError) as e:
print(f"Failed to upload file: {e}")
return
# ----------------------------------------------------------------------
# 3. Prepare conversion settings to transform Excel → plain text
# ----------------------------------------------------------------------
convert_api = ConvertApi(api_client)
file_info = FileInfo()
file_info.file_path = remote_excel_path # source file in cloud storage
txt_options = TxtConvertOptions()
# (optional) you can limit conversion to specific pages:
# txt_options.page_number = 1
# txt_options.page_count = 1
convert_settings = ConvertSettings()
convert_settings.file_info = file_info
convert_settings.format = "txt" # target format
convert_settings.output_path = "sample.txt" # result file name in cloud storage
convert_settings.options = txt_options
# ----------------------------------------------------------------------
# 4. Execute conversion
# ----------------------------------------------------------------------
try:
conversion_result = convert_api.convert(convert_settings)
# The result contains a URL to download the converted file
print(f"Conversion succeeded. Download URL: {conversion_result.url}")
except ApiException as e:
print(f"Conversion failed: {e}")
if __name__ == "__main__":
main()
注意: 此程式碼範例展示了核心功能。 在將其用於您的專案之前,請確保更新所有檔案路徑和設定值以符合實際環境,驗證已正確安裝所有必需的相依項,並在開發環境中徹底測試。 若遇到任何問題,請參閱官方文件或聯繫支援團隊以獲得協助。
使用 cURL 和 REST API 將 Excel 轉換為文字
如果您偏好純粹的 REST 方法,則可以使用 cURL 命令執行相同的轉換。
- 取得存取權杖
curl -X POST "https://api.groupdocs.cloud/v2.0/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"
- 上傳來源 Excel 檔案
curl -X PUT "https://api.groupdocs.cloud/v2.0/storage/file/sample.xlsx" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary @sample.xlsx
- 開始轉換為 TXT
curl -X POST "https://api.groupdocs.cloud/v2.0/conversion/convert" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"fileInfo": { "filePath": "sample.xlsx" },
"format": "txt",
"outputPath": "sample.txt",
"options": {}
}'
- 下載已轉換的 TXT 檔案
curl -X GET "https://api.groupdocs.cloud/v2.0/storage/file/sample.txt" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-o sample.txt
這些指令示範了從驗證到下載的完整生命週期。欲了解更多參數和錯誤處理,請參閱 API 參考。
設定 Excel 轉換設定
SDK 提供了多種選項來自訂輸出。以下是 Excel 轉 TXT 轉換中最實用的設定:
- Page Number - 從特定工作表或頁面開始轉換。
txt_options.page_number = 1 - Page Count - 限制要轉換的工作表/頁面數量。
txt_options.page_count = 2 - Output Path - 定義雲端儲存中生成的 TXT 檔案的名稱和位置。
convert_settings.output_path = "output/sample.txt"
其他進階選項,例如 encoding 或 preserveFormatting,可在 API 參考中取得;請探索它們以符合您的精確需求。
最後的想法
將 Excel 工作簿轉換為純文字的 Python 程式現在變得簡單且可重複,這要歸功於 GroupDocs.Conversion Cloud SDK for Python。該 SDK 在背後處理身份驗證、檔案儲存與轉換,讓您專注於業務邏輯。請記得在 定價頁面 查看授權選項,並在投入生產前取得用於評估的 臨時授權。透過提供的程式碼和 cURL 範例,您可以將 Excel‑to‑TXT 轉換整合到任何基於 Python 的工作流程或微服務中。
常見問題
在 Python 中將 Excel 工作簿轉換為文字的最簡單方法是什麼?
使用 GroupDocs.Conversion Cloud SDK for Python。它抽象了 REST 調用,並提供了乾淨的 Python 風格 API,用於上傳、轉換和下載文件。我可以只轉換 Excel 工作簿中的特定工作表或頁面嗎?
是的。 在TxtConvertOptions物件上設定page_number和page_count以針對特定工作表。 詳情請參閱 API reference。我需要 GroupDocs 帳戶才能使用 SDK �嗎?
需要一個有效的 GroupDocs Cloud 帳戶,並具備客戶端 ID 和密鑰。您可以在 GroupDocs 入口網站上建立帳戶,並從儀表板取得憑證。Excel 轉 TXT 是否有檔案大小限制?
雲端服務支援最多 200 MB 的檔案進行轉換。較大的檔案應在上傳前分割或分批處理。
