> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lance.so/llms.txt
> Use this file to discover all available pages before exploring further.

# Export to CSV

> Export selected leads/prospects to a downloadable CSV file

This endpoint exports selected leads to a CSV file. It supports both manual selection (specific IDs) and bulk selection (range-based with filters).

## How It Works

1. **Resolve Selection**: The selection payload is resolved to actual lead IDs based on the mode
2. **Field Selection**: Determines which fields to include based on `exportFields` or uses defaults
3. **Generate CSV**: Builds CSV content with headers and data rows
4. **File Download**: Returns the CSV as a file attachment

<Note>
  The response is a binary CSV file download, not JSON. The `X-Export-Count`
  header contains the number of exported records.
</Note>

## Request

### Body Parameters

<ParamField body="selection" type="object" required>
  Selection criteria for which leads to export. Supports two modes: manual (explicit IDs) and bulk (range-based).

  <Expandable title="Selection Object">
    <ParamField body="mode" type="string" required>
      Selection mode type.

      **Allowed values:**

      * `manual` - Select specific leads by ID
      * `bulk` - Select a range of leads based on filters and position
    </ParamField>

    <ParamField body="startIndex" type="integer">
      Starting position for bulk selection (0-based). Only used in `bulk` mode.

      **Constraints:** Must be >= 0
    </ParamField>

    <ParamField body="targetCount" type="integer">
      Number of leads to select starting from `startIndex`. Only used in `bulk` mode.

      **Constraints:**

      * Minimum: 1
      * Maximum: 1000
    </ParamField>

    <ParamField body="excludedIds" type="string[]">
      Array of lead IDs to exclude from bulk selection.

      Used to remove specific leads from the bulk range.
    </ParamField>

    <ParamField body="includedIds" type="string[]">
      Array of lead IDs to explicitly include.

      * In `manual` mode: The complete list of leads to export
      * In `bulk` mode: Additional leads to include outside the bulk range
    </ParamField>

    <ParamField body="filters" type="object">
      Search filters to reproduce the exact search context. Required for `bulk` mode to resolve the selection.

      See the [People Search Filters](#filters-reference) section for the full filter schema.
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="exportFields" type="string[]">
  Array of field IDs to include in the export. If not specified, uses default
  fields. **Default fields:** `name`, `emails`, `phones`, `linkedinUrl`, `city`,
  `country`, `jobTitle`, `companyName` See [Available Export
  Fields](#available-export-fields) for all options.
</ParamField>

## Response

The response is a CSV file download with the following headers:

<ResponseField name="Content-Type" type="header">
  `text/csv; charset=utf-8`
</ResponseField>

<ResponseField name="Content-Disposition" type="header">
  `attachment; filename="lance-prospects-{YYYY - MM - DD}.csv"` The filename
  includes the current date.
</ResponseField>

<ResponseField name="X-Export-Count" type="header">
  The number of records exported (as a string).
</ResponseField>

### CSV Format

The CSV file contains:

* **Header row**: Column labels based on selected fields
* **Data rows**: One row per lead with values for each selected field
* Values containing commas, quotes, or newlines are properly escaped
* UTF-8 encoding

## Available Export Fields

Fields are organized by category. Use the `id` value in the `exportFields` array.

### Contact Information

| Field ID      | Label        | Description                          |
| ------------- | ------------ | ------------------------------------ |
| `name`        | Name         | Full name (first + last)             |
| `emails`      | Email(s)     | All email addresses, comma-separated |
| `phones`      | Phone(s)     | All phone numbers, comma-separated   |
| `linkedinUrl` | LinkedIn URL | Person's LinkedIn profile URL        |

### Location Information

| Field ID     | Label       | Description          |
| ------------ | ----------- | -------------------- |
| `city`       | City        | Person's city        |
| `postalCode` | Postal Code | Person's postal code |
| `country`    | Country     | Person's country     |

### Professional Information

| Field ID      | Label             | Description                       |
| ------------- | ----------------- | --------------------------------- |
| `jobTitle`    | Job Title         | Current job title                 |
| `seniority`   | Seniority         | Seniority level                   |
| `departments` | Departments       | Departments, comma-separated      |
| `functions`   | Functions         | Job functions, comma-separated    |
| `industry`    | Industry (Person) | Person's industry                 |
| `skills`      | Skills            | Skills, comma-separated           |
| `languages`   | Languages         | Languages spoken, comma-separated |

### Company Information

| Field ID             | Label                    | Description                      |
| -------------------- | ------------------------ | -------------------------------- |
| `companyName`        | Company Name             | Current company name             |
| `companyLegalName`   | Company Legal Name       | Company's legal registered name  |
| `companyWebsite`     | Company Website          | Company website URL              |
| `companyLinkedin`    | Company LinkedIn         | Company LinkedIn page URL        |
| `companyPhone`       | Company Phone(s)         | Company phone numbers            |
| `companyCity`        | Company City (HQ)        | Company headquarters city        |
| `companyPostalCode`  | Company Postal Code (HQ) | Company headquarters postal code |
| `companyCountry`     | Company Country (HQ)     | Company headquarters country     |
| `companyIndustry`    | Company Industry         | Company's industry               |
| `companyHeadcount`   | Company Headcount        | Employee count range             |
| `companyRevenue`     | Company Revenue          | Revenue range                    |
| `companyFoundedYear` | Company Founded Year     | Year company was founded         |
| `companySummary`     | Company Summary          | AI-generated company summary     |

<RequestExample>
  ```bash cURL (Manual Selection) theme={null}
  curl -X POST "https://app.lance.so/api/v1/operations/export" \
    -H "Authorization: Bearer <token>" \
    -H "Content-Type: application/json" \
    -o "leads-export.csv" \
    -d '{
      "selection": {
        "mode": "manual",
        "includedIds": [
          "550e8400-e29b-41d4-a716-446655440000",
          "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
        ]
      },
      "exportFields": ["name", "emails", "phones", "jobTitle", "companyName"]
    }'
  ```

  ```bash cURL (Bulk Selection) theme={null}
  curl -X POST "https://app.lance.so/api/v1/operations/export" \
    -H "Authorization: Bearer <token>" \
    -H "Content-Type: application/json" \
    -o "leads-export.csv" \
    -d '{
      "selection": {
        "mode": "bulk",
        "startIndex": 0,
        "targetCount": 100,
        "excludedIds": ["excluded-id-1"],
        "filters": {
          "contact": {
            "location": {
              "any": {
                "include": ["San Francisco, CA"]
              }
            }
          }
        }
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("/api/v1/operations/export", {
    method: "POST",
    headers: {
      Authorization: "Bearer <token>",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      selection: {
        mode: "manual",
        includedIds: [
          "550e8400-e29b-41d4-a716-446655440000",
          "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
        ],
      },
      exportFields: ["name", "emails", "phones", "jobTitle", "companyName"],
    }),
  });

  // Get the export count from headers
  const exportCount = response.headers.get("X-Export-Count");

  // Download the CSV
  const blob = await response.blob();
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "leads-export.csv";
  a.click();
  ```

  ```typescript TypeScript theme={null}
  interface BulkSelectionPayload {
    mode: "manual" | "bulk";
    startIndex?: number;
    targetCount?: number;
    excludedIds?: string[];
    includedIds?: string[];
    filters?: PeopleSearchFilters;
  }

  interface ExportRequest {
    selection: BulkSelectionPayload;
    exportFields?: string[];
  }

  const response = await fetch("/api/v1/operations/export", {
    method: "POST",
    headers: {
      Authorization: "Bearer <token>",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      selection: {
        mode: "manual",
        includedIds: [
          "550e8400-e29b-41d4-a716-446655440000",
          "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
        ],
      },
      exportFields: ["name", "emails", "phones", "jobTitle", "companyName"],
    } satisfies ExportRequest),
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error);
  }

  const exportCount = parseInt(response.headers.get("X-Export-Count") || "0", 10);
  const blob = await response.blob();
  ```
</RequestExample>

<ResponseExample>
  ```csv Success Response (CSV File) theme={null}
  Name,Email(s),Phone(s),Job Title,Company Name
  John Smith,john@example.com,+1-555-0100,Software Engineer,Acme Corp
  Jane Doe,"jane@example.com, jane.doe@personal.com",+1-555-0101,Product Manager,Tech Inc
  ```

  ```json Error Response (No Data) theme={null}
  {
    "error": "No data to export"
  }
  ```

  ```json Error Response (Validation Error) theme={null}
  {
    "error": {
      "code": "VALIDATION_ERROR",
      "message": "Invalid selection mode"
    }
  }
  ```

  ```json Error Response (Invalid Fields) theme={null}
  {
    "error": {
      "code": "INTERNAL_ERROR",
      "message": "No valid export fields specified"
    }
  }
  ```
</ResponseExample>

## Error Codes

| Status Code | Error Code         | Description                                       |
| ----------- | ------------------ | ------------------------------------------------- |
| `400`       | -                  | No data to export (selection resolved to 0 leads) |
| `400`       | `VALIDATION_ERROR` | Invalid request body or missing required fields   |
| `500`       | `INTERNAL_ERROR`   | Server error during export generation             |

## Filters Reference

For `bulk` mode, the `filters` object uses the People Search schema. Key filter sections include:

### Contact Filters

* `fullName` - Filter by person name
* `location` - Filter by location (city, country)
* `seniority` - Filter by seniority level (entry, mid-level, senior, director, c\_suite, etc.)
* `departmentAndFunction` - Filter by department or function
* `skill` - Filter by skills
* `education` - Filter by school, degree, or field of study
* `experience` - Filter by current or previous job titles

### Account (Company) Filters

* `nameOrDomain` - Filter by company name or domain
* `industry` - Filter by company industry
* `location` - Filter by company location
* `employeeSize` - Filter by company size range
* `revenue` - Filter by company revenue range
* `type` - Filter by company type (public, private, etc.)

## Notes

* **Maximum bulk selection**: 1000 leads per export
* **Default fields**: If no `exportFields` specified, exports: name, emails, phones, linkedinUrl, city, country, jobTitle, companyName
* **CSV escaping**: Values with commas, quotes, or newlines are automatically quoted and escaped
* **Filename**: Automatically generated with current date: `lance-prospects-YYYY-MM-DD.csv`
* **Authentication**: Requires authentication; exports are scoped to the authenticated organization
