🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import { readFile } from 'node:fs/promises';
import debug from 'debug';
import * as xlsx from 'xlsx';
import { isFileParseBudgetError } from '../../fileParseBudget';
import type { DocumentPage, FileLoaderInterface } from '../../types';
import { promptTemplate } from './prompt';
import { clampSheetRefToData } from './sheetBounds';
import { preflightXlsxZip } from './zipBudget';
const log = debug('file-loaders:excel');
/**
* Converts sheet data (array of objects) to a Markdown table string.
* Handles empty sheets and escapes pipe characters.
*/
function sheetToMarkdownTable(jsonData: Record<string, any>[]): string {
log('Converting sheet data to Markdown table, rows:', jsonData?.length || 0);
if (!jsonData || jsonData.length === 0) {
log('Sheet is empty, returning placeholder message');
return '*Sheet is empty or contains no data.*';
}
const toCell = (value: unknown) =>
// Handle null/undefined and escape pipe characters within cells
value === null || value === undefined ? '' : String(value).replaceAll('|', '\\|').trim();
/**
* Keep only columns that hold a value in some row, and rows with at least one value.
* Formatting or stray edits can stretch a sheet's used range across thousands of blank columns
* and rows (the headers show up as `__EMPTY_n`); rendering every blank cell turned a 200 KB
* workbook into 60+ MB of `| | |` text.
*/
const headers = Object.keys(jsonData[0] || {}).filter(
(header) => !header.startsWith('__EMPTY') || jsonData.some((row) => toCell(row[header]) !== ''),
);
log('Sheet headers:', headers);
if (headers.length === 0) {
log('Sheet has no headers, returning placeholder message');
return '*Sheet has headers but no data.*';
}
const headerRow = `| ${headers.join(' | ')} |`;
const separatorRow = `| ${headers.map(() => '---').join(' | ')} |`;
log('Building data rows for Markdown table');
const dataRows = jsonData
.map((row) => headers.map((header) => toCell(row[header])))
.filter((cells) => cells.some((cell) => cell !== ''))
.map((cells) => `| ${cells.join(' | ')} |`)
.join('\n');
const result = `${headerRow}\n${separatorRow}\n${dataRows}`;
log('Markdown table created, length:', result.length);
return result;
}
/**
* Loads Excel files (.xlsx, .xls) using the 'xlsx' library.
* Each sheet becomes a DocumentPage containing a Markdown table generated by sheetToMarkdownTable.
*/
export class ExcelLoader implements FileLoaderInterface {
async loadPages(filePath: string): Promise<DocumentPage[]> {
log('Loading Excel file:', filePath);
const pages: DocumentPage[] = [];
try {
// Use readFile for async operation compatible with other loaders
log('Reading Excel file as buffer');
const dataBuffer = await readFile(filePath);
log('Excel file read successfully, size:', dataBuffer.length, 'bytes');
// Refuse oversized ZIP structures before SheetJS inflates them
await preflightXlsxZip(dataBuffer);
log('Parsing Excel workbook');
const workbook = xlsx.read(dataBuffer, { type: 'buffer' });
log('Excel workbook parsed successfully, sheets:', workbook.SheetNames.length);
for (const sheetName of workbook.SheetNames) {
log(`Processing sheet: ${sheetName}`);
const worksheet = workbook.Sheets[sheetName];
// A declared used range can span a million styled-but-empty rows: clamp it to the real data
clampSheetRefToData(worksheet);
// Use sheet_to_json to get array of objects for our custom markdown function
const jsonData = xlsx.utils.sheet_to_json<Record<string, any>>(worksheet, {
// Get formatted strings, not raw values
defval: '',
raw: false, // Use empty string for blank cells
});
log(`Sheet ${sheetName} converted to JSON, rows:`, jsonData.length);
// Convert to markdown using YOUR helper function
const tableMarkdown = sheetToMarkdownTable(jsonData);
const lines = tableMarkdown.split('\n');
const lineCount = lines.length;
const charCount = tableMarkdown.length;
log(`Sheet ${sheetName} converted to Markdown, lines: ${lineCount}, chars: ${charCount}`);
pages.push({
// Trim whitespace
charCount,
lineCount,
metadata: {
sheetName,
},
pageContent: tableMarkdown.trim(),
});
log(`Added sheet ${sheetName} as page`);
}
if (pages.length === 0) {
log('Excel file contains no sheets, creating empty page with error');
pages.push({
charCount: 0,
lineCount: 0,
metadata: {
error: 'Excel file contains no sheets.',
},
pageContent: '',
});
}
log('Excel loading completed, total pages:', pages.length);
return pages;
} catch (e) {
// A budget refusal is not a corrupt file: let callers tell the user the file is too large
if (isFileParseBudgetError(e)) throw e;
const error = e as Error;
log('Error encountered while loading Excel file');
console.error(`Error loading Excel file ${filePath}: ${error.message}`);
const errorPage: DocumentPage = {
charCount: 0,
lineCount: 0,
metadata: {
error: `Failed to load Excel file: ${error.message}`,
},
pageContent: '',
};
log('Created error page for failed Excel loading');
return [errorPage];
}
}
/**
* Aggregates content from Excel sheets (Markdown tables).
* Adds the sheet name as a header before each table.
* @param pages Array of DocumentPage objects from loadPages.
* @returns Aggregated content as a string.
*/
async aggregateContent(pages: DocumentPage[]): Promise<string> {
log('Aggregating content from', pages.length, 'Excel pages');
const result = promptTemplate(pages);
log('Excel content aggregated successfully, length:', result.length);
return result;
}
}