0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google Drive上のExcelファイルをGoogleスプレッドシート形式で複製する

Posted at

概要

Google Drive に保存されている Excel ファイル(.xlsx)を、同じGoogle Drive上にGoogle スプレッドシート形式で複製するための GAS(Google Apps Script)です。

Excel ファイルはそのままでは IMPORTRANGE 関数や他の GAS から参照できないため、本スクリプトで「別のスプレッドシートへコピー」を自動化します。

なお、ネット上のサンプルコードを試したところ拡張子が .pdf.doc に変わってしまう現象が起きたため、動作が安定する方法を改めて検討・実装しました。

Googleドライブ上のExcelファイル

Googleドライブ上のExcelファイルは緑色のラベルで「.XLSX」と表示されます。

スクリーンショット 2025-01-31 9.24.13(2).png

DriveAPIを追加

Apps Script画面の「サービス」からDrive API V2を追加してください。

スクリーンショット 2025-01-31 9.16.02(2).png

Script

以下のコードをApps Scriptに貼り付けて保存します。

const sourceFileId = 'XXXX'; // 元のExcelファイルのID
const existingSpreadsheetId = 'YYYY'; // 上書きしたいスプレッドシートのID

function excel_to_gsheet_converter() {
    // Excelファイルを取得
    const sourceFile = DriveApp.getFileById(sourceFileId);

    // ExcelファイルをGoogleスプレッドシートに変換して上書き
    overwriteSpreadsheet(sourceFile, existingSpreadsheetId);
}

function overwriteSpreadsheet(file, spreadsheetId) {
    try {
        // ExcelファイルをGoogleスプレッドシートに変換するためにバイナリデータを取得
        const blob = file.getBlob();

        // 既存のスプレッドシートに内容を上書き
        const updatedFile = Drive.Files.update(
            {
                title: DriveApp.getFileById(spreadsheetId).getName(), // ファイル名は変更しない
                mimeType: MimeType.GOOGLE_SHEETS // MIMEタイプはGoogleスプレッドシート
            },
            spreadsheetId,
            blob
        );
        Logger.log(`ファイルを上書きしました: ${updatedFile.id}`);
    } catch (e) {
        Logger.log(`エラーが発生しました: ${e.message}`);
    }
}

トリガーを設定

  1. エディタ右側の「トリガー」 から「+」をクリック
  2. 実行する関数に excelToGsheetConverter を選択
  3. イベントのソース:時間主導型
  4. 時間ベースのタイプ:時間ベースのタイマー
  5. 時間の間隔:例)1 時間おき
  6. 保存 をクリックして完了

スクリーンショット 2025-01-31 9.20.00(2).png

以上です。
このスクリプトを有効にすると、指定した間隔でExcelファイルが自動的にGoogleスプレッドシートへ複製され、他のシートやGASから参照できるようになります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?