Automatizacion de hojas de calculo con Claude Code
Aprenda sobre automatizacion de hojas de calculo usando Claude Code. Incluye ejemplos practicos de codigo.
スプレッドシート連携を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 gratuito: Hoja de trucos de Claude Code en 5 minutos
Solo deja tu correo y te enviaremos al instante la hoja de trucos en una página A4.
Cuidamos tus datos personales y nunca enviamos spam.
Sobre el autor
Masa
Ingeniero apasionado por Claude Code. Dirige claudecode-lab.com, un medio tecnológico en 10 idiomas con más de 2.000 páginas.
Artículos relacionados
7 comprobaciones antes de publicar cada día un artículo multilingüe sobre Claude Code
Una lista práctica para publicar artículos multilingües sobre Claude Code todos los días sin olvidar idiomas, romper CTAs ni dejar páginas antiguas en producción.
Que es Codex Automations y como dejar que la IA gestione contenido mientras duermes
Guia practica para usar Codex Automations en analitica, articulos, CTA, despliegue y monetizacion.
Claude Code × GCP Cloud Functions Guía Completa | Desarrollo Serverless Ultrarrápido
Optimiza GCP Cloud Functions con Claude Code. Implementa triggers HTTP/Pub/Sub/Firestore, pruebas locales y automatización de despliegues con ejemplos de código reales de la experiencia de Masa.