Automatisation de tableurs avec Claude Code
Découvrez automatisation de tableurs avec Claude Code. Conseils pratiques et exemples de code inclus.
スプレッドシート連携を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公式ドキュメントを参照してください。
PDF gratuit : aide-mémoire Claude Code en 5 minutes
Laissez simplement votre e-mail et nous vous enverrons immédiatement l'aide-mémoire A4 en PDF.
Nous traitons vos données avec soin et n'envoyons jamais de spam.
À propos de l'auteur
Masa
Ingénieur passionné par Claude Code. Il gère claudecode-lab.com, un média tech en 10 langues avec plus de 2 000 pages.
Articles similaires
7 vérifications avant de publier chaque jour un article multilingue sur Claude Code
Une checklist pratique pour publier des articles multilingues sur Claude Code chaque jour sans oublier une langue, casser les CTA ou laisser l’ancien contenu en production.
Codex Automations : confier l'analyse, les articles et le deploiement a l'IA
Guide pratique pour utiliser Codex Automations dans une operation de contenu orientee monetisation.
Claude Code × GCP Cloud Functions Guide Complet | Développement Serverless Ultra-Rapide
Optimisez GCP Cloud Functions avec Claude Code. Implémentez des triggers HTTP/Pub/Sub/Firestore, des tests locaux et l'automatisation des déploiements avec des exemples de code réels de l'expérience de Masa.