Automating Spreadsheet Integration with Claude Code
Learn about automating spreadsheet integration using Claude Code. Practical tips and code examples included.
スプレッドシート連携をClaude Codeで効率化する
業務システムではExcelやGoogle Sheetsとのデータ連携が頻繁に発生します。Claude Codeを使えば、ファイルの読み書き、データ変換、API連携まで一気に実装できます。
Excelファイルの読み込みと解析
SheetJS(xlsx)を使ったExcelファイルの読み込みです。
> xlsxライブラリでExcelファイルを読み込んで、型安全なオブジェクト配列に変換する関数を作って。
> ヘッダー行を型のキーとして使って。
import * as XLSX from "xlsx";
export function readExcel<T extends Record<string, unknown>>(
filePath: string,
sheetName?: string
): T[] {
const workbook = XLSX.readFile(filePath);
const sheet = sheetName
? workbook.Sheets[sheetName]
: workbook.Sheets[workbook.SheetNames[0]];
if (!sheet) throw new Error(`Sheet not found: ${sheetName}`);
const data = XLSX.utils.sheet_to_json<T>(sheet, {
defval: "",
raw: false,
});
return data;
}
// Usage example
interface Employee {
名前: string;
部署: string;
メール: string;
入社日: string;
}
const employees = readExcel<Employee>("./data/employees.xlsx");
console.log(employees);
// [
// { 名前: "田中太郎", 部署: "開発部", メール: "[email protected]", 入社日: "2024-04-01" },
// ...
// ]
Excelファイルの生成
データベースのデータをExcelに出力する機能です。
import * as XLSX from "xlsx";
interface ExportOptions {
sheetName?: string;
columnWidths?: number[];
headerStyle?: boolean;
}
export function createExcel<T extends Record<string, unknown>>(
data: T[],
outputPath: string,
options: ExportOptions = {}
) {
const { sheetName = "Sheet1", columnWidths } = options;
const worksheet = XLSX.utils.json_to_sheet(data);
// カラム幅の設定
if (columnWidths) {
worksheet["!cols"] = columnWidths.map((w) => ({ wch: w }));
} else {
// Auto-calculate width
const headers = Object.keys(data[0] || {});
worksheet["!cols"] = headers.map((header) => {
const maxLen = Math.max(
header.length * 2, // 日本語は2倍
...data.map((row) => String(row[header] || "").length)
);
return { wch: Math.min(maxLen + 2, 50) };
});
}
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
XLSX.writeFile(workbook, outputPath);
}
// Usage example
const salesData = [
{ 月: "2026年1月", 売上: 1200000, 件数: 45 },
{ 月: "2026年2月", 売上: 1500000, 件数: 52 },
{ 月: "2026年3月", 売上: 1350000, 件数: 48 },
];
createExcel(salesData, "./output/sales-report.xlsx", {
sheetName: "売上レポート",
});
Google Sheets APIとの連携
Google Sheetsのデータをリアルタイムで読み書きする実装です。
import { google } from "googleapis";
const auth = new google.auth.GoogleAuth({
keyFile: "./credentials.json",
scopes: ["https://www.googleapis.com/auth/spreadsheets"],
});
const sheets = google.sheets({ version: "v4", auth });
export async function readGoogleSheet(
spreadsheetId: string,
range: string
): Promise<string[][]> {
const response = await sheets.spreadsheets.values.get({
spreadsheetId,
range,
});
return response.data.values || [];
}
export async function writeGoogleSheet(
spreadsheetId: string,
range: string,
values: (string | number)[][]
) {
await sheets.spreadsheets.values.update({
spreadsheetId,
range,
valueInputOption: "USER_ENTERED",
requestBody: { values },
});
}
export async function appendToGoogleSheet(
spreadsheetId: string,
range: string,
values: (string | number)[][]
) {
await sheets.spreadsheets.values.append({
spreadsheetId,
range,
valueInputOption: "USER_ENTERED",
requestBody: { values },
});
}
// Usage example
const data = await readGoogleSheet("SPREADSHEET_ID", "売上!A1:D100");
console.log(data);
await appendToGoogleSheet("SPREADSHEET_ID", "売上!A:D", [
["2026年4月", 1400000, 50, "=B5/C5"],
]);
CSVとExcelの相互変換
import * as XLSX from "xlsx";
import fs from "fs";
export function csvToExcel(csvPath: string, excelPath: string) {
const csv = fs.readFileSync(csvPath, "utf-8");
const workbook = XLSX.read(csv, { type: "string" });
XLSX.writeFile(workbook, excelPath);
}
export function excelToCsv(excelPath: string, csvPath: string, sheetIndex = 0) {
const workbook = XLSX.readFile(excelPath);
const sheetName = workbook.SheetNames[sheetIndex];
const csv = XLSX.utils.sheet_to_csv(workbook.Sheets[sheetName]);
fs.writeFileSync(csvPath, csv);
}
PDF帳票の出力と組み合わせる場合はPDF生成機能を、データの可視化についてはデータ可視化の実装もご覧ください。Claude Codeの基本操作は入門ガイドを参照してください。
Summary
Claude Codeを使えば、Excelの読み書き、Google Sheets連携、データ変換といったスプレッドシート関連の処理を短時間で実装できます。業務で頻出する「DBからExcel出力」「CSVからExcel変換」などのパターンは、自然言語で要件を伝えるだけで完成します。
詳しくはClaude Code公式ドキュメントを参照してください。
Free PDF: Claude Code Cheatsheet in 5 Minutes
Just enter your email and we'll send you the single-page A4 cheatsheet right away.
We handle your data with care and never send spam.
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
7 Deployment Checks Before You Publish a Multilingual Claude Code Article Every Day
A practical checklist for publishing daily multilingual Claude Code articles without missing locales, breaking CTAs, or shipping stale pages.
Codex Automations for Content Ops: A Daily Revenue Workflow for Claude Code Sites
Use Codex Automations to turn analytics, article updates, CTA improvements, deployment, and verification into a daily revenue workflow.
Claude Code × GCP Cloud Functions Complete Guide | Rapid Serverless Function Development
Streamline GCP Cloud Functions with Claude Code. Implement HTTP/Pub/Sub/Firestore triggers, local testing, and deployment automation with real-world code examples from Masa's experience.
Related Products
50 Battle-Tested Claude Code Prompt Templates
Copy, paste, ship. 50 production-ready prompts.
Use proven prompts for code review, refactoring, testing, documentation, debugging, architecture, and incident response.
The Complete Claude Code Setup & Configuration Guide
From install to team-ready workflow.
A practical guide to installation, CLAUDE.md, hooks, MCP servers, permissions, IDE setup, and CI/CD workflows.