Excelブックから生テキストを抽出することは、データパイプラインを構築したりシンプルなレポートを作成したりする際に頻繁に必要とされます。PythonでExcel Workbookをテキストに変換する方法を知りたい場合は、GroupDocs.Conversion Cloud SDK for Python が簡単に行えます。このガイドでは、SDKのインストール、ブックのアップロード、変換オプションの設定、そしてプレーンなTXT 結果の取得手順を説明します。最後まで読むと、再利用可能なスクリプトとRESTベースの自動化用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 ストレージにアップロードします。ファイルがすでにクラウドにある場合は、この手順は省略できます。
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 を使用して、プレーンテキストファイルをローカル環境にダウンロードするか、アプリケーションでさらに処理してください。
Tip: 簡単な
requests.get()呼び出しでダウンロードを自動化でき、変換リクエストに使用したのと同じアクセストークンで認証を処理します。
これらの手順に従うことで、GroupDocs ライブラリを使用して Python で Excel ワークブックをテキストに変換する方法 の完全なワークフローが手に入ります。
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‑to‑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"
APIリファレンスでは、encoding や preserveFormatting などの他の高度なオプションが利用可能です。要件に合わせてそれらを確認してください。
最終的な考え
PythonでExcelブックをプレーンテキストに変換することが、GroupDocs.Conversion Cloud SDK for Pythonのおかげでシンプルかつ再利用可能なプロセスになりました。SDKは認証、ファイル保存、変換を裏で処理し、ビジネスロジックに集中できるようにします。製品の価格ページでライセンスオプションを確認し、運用開始前に評価用の一時ライセンスを取得してください。提供されたコードとcURLの例を使用すれば、Excel‑to‑TXT変換を任意のPythonベースのワークフローやマイクロサービスに統合できます。
よくある質問
Excel ワークブックを Python でテキストに変換する最も簡単な方法は何ですか?
Use the GroupDocs.Conversion Cloud SDK for Python. It abstracts the REST calls and provides a clean Pythonic API for uploading, converting, and downloading files.Excelブックの特定のシートやページだけを変換できますか?
はい。TxtConvertOptionsオブジェクトのpage_numberとpage_countを設定して、特定のシートを対象にします。詳細は API reference をご覧ください。SDKを使用するためにGroupDocsアカウントは必要ですか?
有効なGroupDocs Cloudアカウント(クライアントIDとシークレットが必要)を持っている必要があります。GroupDocsポータルでアカウントを作成し、ダッシュボードから認証情報を取得できます。Excel から TXT への変換にファイルサイズの制限はありますか?
クラウドサービスは変換のために最大 200 MB のファイルをサポートしています。より大きなファイルは、アップロード前に分割するか、チャンクに分けて処理する必要があります。
