Created
April 18, 2025 04:21
-
-
Save lushkovsky-s/d1a060a753dc27ed7e74349ddc825ded to your computer and use it in GitHub Desktop.
MCP to read XLSX table (by data/url)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { WorkerEntrypoint } from 'cloudflare:workers' | |
import { ProxyToSelf } from 'workers-mcp' | |
import XLSX from 'xlsx' | |
export default class MCPTableReader extends WorkerEntrypoint<Env> { | |
/** | |
* Read an xlsx file from a url or binary data | |
* @param source {string | ArrayBuffer | Uint8Array} the url or binary data to read | |
* @param sheetName {string} the name of the sheet to read | |
* @param startRow {number} the starting row to read | |
* @param endRow {number} the ending row to read | |
* @return {string} the contents as a string | |
*/ | |
async readXlsx( | |
source: string | ArrayBuffer | Uint8Array, | |
sheetName: string = 'Sheet1', | |
startRow: number = 0, | |
endRow: number = 100, | |
) { | |
try { | |
let data: Uint8Array; | |
if (typeof source === 'string') { | |
const response = await fetch(source, { | |
headers: { | |
'accept': '*/*', | |
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', | |
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36' | |
} | |
}); | |
if (!response.ok) { | |
throw new Error(`Failed to download XLSX: ${response.status}`); | |
} | |
const arrayBuffer = await response.arrayBuffer(); | |
data = new Uint8Array(arrayBuffer); | |
} else { | |
data = source instanceof Uint8Array ? source : new Uint8Array(source); | |
} | |
const workbook = XLSX.read(data, { type: 'array' }); | |
const sheet = workbook.Sheets[sheetName]; | |
if (!sheet) { | |
throw new Error(`Sheet "${sheetName}" not found`); | |
} | |
const rows = XLSX.utils.sheet_to_json(sheet, { header: 1, range: startRow }); | |
const selectedRows = rows.slice(0, endRow - startRow); | |
return `XLSX data read successfully (rows ${startRow} - ${endRow}):\n ${JSON.stringify(selectedRows)}`; | |
} catch (error) { | |
console.error('Error reading XLSX:', error); | |
throw error; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment