Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

3.3 KB
Raw Blame
import { createAction, Property } from '@activepieces/pieces-framework';
import {
  httpClient,
  HttpMethod,
  AuthenticationType,
} from '@activepieces/pieces-common';
import { googleSheetsAuth } from '../common/common';
import { commonProps } from '../common/props';
import { areSheetIdsValid, getAccessToken } from '../common/common';
import { exportSheetActionOutputSchema } from '../output-schemas';

export const exportSheetAction = createAction({
  name: 'export_sheet',
  classification: 'READ',
  displayName: 'Export Worksheet',
  description: 'Download a worksheet as a CSV or TSV file.',
  audience: 'human',
  aiMetadata: {
    description:
      'Exports a worksheet as a CSV or TSV file, returned either as a file reference or as raw text. Use when an agent needs the sheet contents in a flat delimited format for downstream processing or attachment. Read-only and idempotent.',
    idempotent: true,
  },
  auth: googleSheetsAuth,
  propertyGroups: [
    {
      key: 'spreadsheet',
      display: 'section',
      label: 'Spreadsheet',
      icon: 'file',
      props: ['spreadsheetId', 'sheetId'],
    },
    {
      key: 'export',
      display: 'section',
      label: 'Export',
      icon: 'paperclip',
      props: ['format', 'returnAsText'],
    },
  ],
  props: {
    ...commonProps,
    format: Property.StaticDropdown({
      displayName: 'Export Format',
      description: 'Select the file type to export the sheet as.',
      required: true,
      defaultValue: 'csv',
      options: {
        disabled: false,
        options: [
          { label: 'Comma Separated Values (.csv)', value: 'csv' },
          { label: 'Tab Separated Values (.tsv)', value: 'tsv' },
        ],
      },
    }),
    returnAsText: Property.Checkbox({
      displayName: 'Return as Text',
      description: 'Return the exported data as text instead of a file.',
      required: false,
      defaultValue: false,
    }),
  },
  outputSchema: exportSheetActionOutputSchema,
  async run({ propsValue, auth, files }) {
    const { spreadsheetId, sheetId, format, returnAsText } = propsValue;

    if (!areSheetIdsValid(spreadsheetId, sheetId)) {
      throw new Error('Please select a spreadsheet and sheet first.');
    }

    const spreadsheet_id = spreadsheetId as string;
    const sheet_id = sheetId as number;

    const exportUrl = `https://docs.google.com/spreadsheets/d/${spreadsheet_id}/export?format=${format}&id=${spreadsheet_id}&gid=${sheet_id}`;

    try {
      const response = await httpClient.sendRequest({
        method: HttpMethod.GET,
        url: exportUrl,
        authentication: {
          type: AuthenticationType.BEARER_TOKEN,
          token: await getAccessToken(auth),
        },
        responseType: 'arraybuffer',
        followRedirects: true,
      });

      if (returnAsText) {
        const textData = Buffer.from(response.body).toString('utf-8');
        return {
          text: textData,
          format,
        };
      } else {
        const filename = `exported_sheet.${format}`;

        const file = await files.write({
          fileName: filename,
          data: Buffer.from(response.body),
        });

        return {
          file,
          filename,
          format,
        };
      }
    } catch (error) {
      throw new Error(`Failed to export sheet: ${error}`);
    }
  },
});