LoginSignup
45
57

ExcelでChatGPTを呼び出して楽をする

Last updated at Posted at 2024-04-03

はじめに

  • Excelで、表の集計でChatGPTを使いたい、と思うことは無いでしょうか?
    • たとえば、大量のアンケートを集計・分析したい、とか・・・
  • 今回、OfficeScriptとChatGPT(OpenAI)を使って処理ができることが分かったので、共有したい

やること

  • 以下のような表をあらかじめ作っておいて、Productの内容をもとに、OpenAIにカフェメニューを挙げさせるサンプルを作る

image.png

コード共有

async function main(workbook: ExcelScript.Workbook) {
  // Get the active worksheet.
  let sheet = workbook.getActiveWorksheet();

  // Get the table
  const table = sheet.getTable("CafeMenuTable"); // "CafeMenuTable" はテーブルの名前に置き換えます

  const tableDataRange = table.getRangeBetweenHeaderAndTotal(); // テーブルのヘッダーと合計行を含む範囲を取得

  const tableData = tableDataRange.getValues();

  for (let i = 0; i < tableData.length; i++) {
    const cellValueB = tableData[i][0]; // B列のセルの値を取得
    const cellValueC = tableData[i][1]; // C列のセルの値を取得

    // OpenAIにセルの値を送信して処理
    const response = await callOpenAI(cellValueB, cellValueC);

    // 結果をテーブルに転記
    const resultCell = tableDataRange.getCell(i, 2); // D列に書き込む
    resultCell.setValue(response);
  }
}


async function callOpenAI(inputTextB: string, inputTextC: string): Promise < string > {
  const EndPoint = "https://xxxxxxxxxxxxxxx.openai.azure.com/openai/deployments/gpt-35-turbo/chat/completions?api-version=2024-02-01";
  const Key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

  const payload = {
    "messages": [
      {
        "role": "system",
        "content": inputTextC
      },
      {
        "role": "user",
        "content": inputTextB
      }
    ],
    "temperature": 0.7,
    "max_tokens": 800,
    "stop": null,
    "stream": false
  };

  const options: RequestInit = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'api-Key': Key
    },
    body: JSON.stringify(payload)
  };

  try {
    const response = await fetch(EndPoint, options);
    // console.log(EndPoint, options);
    if (response.ok) {
      const json: { choices: { message: { content: string } }[] } = await response.json();
      const content = json.choices[0].message.content;
      console.log(content);
      return content;
    } else {
      console.log('APIリクエストに失敗しました' + response.status);
    }
  } catch (error) {
    console.log('エラーが発生しました', error);
  }
}

コードのポイント解説

  • OpenAIのAPIは、Azure OpenAIをベースにしているので、Azureじゃない場合は、リクエストヘッダなど、適宜変更すること
  • テーブルのB列・C列などは決め打ちでデータを取得しているので、たぶんもっといい方法はあると思う
  • テーブル全体を読み取るようにコードを修正しました
    • テーブル名の設定をお忘れなく!

image.png

OfficeScript初めての方向けの補足

  • 以下からスクリプトを追加することができます
    • [自動化] ⇒ [新しいスクリプト]
  • すると、コードエディターの画面が現れるので、上記のコードに書き換えましょう
    • ※OpenAIのFQDNとAPIキーは各自調達の情報を入れること

image.png

  • 準備ができたら、「実行」ボタンでスクリプトが動きます

image.png

実行結果

image.png

45
57
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
45
57