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

# Export Analytics Data

> Export QR Code analytics as downloadable reports in Excel (XLS/XLSX) or PDF format. Ideal for detailed performance reviews, audits, and external analysis in tools like Excel, Google Sheets, or BI dashboards. Authentication required.

## Description

This endpoint allows you to export **comprehensive analytics data** for one or more QR codes over a specific date range.\
The export includes scan details, device and OS data, and geographic insights — formatted for spreadsheet analysis.

You can choose between:

* `.pdf` for easy sharing and presentation-ready reports
* `.xls`\*\*/ \*\* `.xlsx` for advanced Excel-based reportingPurpose

## Query Parameters

| Parameter          | Type                  | Required | Description                                                                                                                                                      |
| :----------------- | :-------------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `from`             | `string (YYYY-MM-DD)` | ✅ Yes    | Start date for analytics data (inclusive).                                                                                                                       |
| `to`               | `string (YYYY-MM-DD)` | ✅ Yes    | End date for analytics data (inclusive). Defaults to current date.                                                                                               |
| `file_format`      | `string`              | ✅ Yes    | Desired export format — must be one of: `xls`, `xlsx`, `pdf`.                                                                                                    |
| `exclude_bot_scan` | `boolean`             | No       | When `true`, bot scans are excluded from all exported analytics. Excel exports gain an additional **Bot Scans** sheet with the bot summary. Defaults to `false`. |

## Request Body

| Field       | Type     | Required | Description                                                        |
| :---------- | :------- | :------- | :----------------------------------------------------------------- |
| `filter_by` | `string` | ✅ Yes    | Specify filter type — either `qrid` or `tags`.                     |
| `q`         | `array`  | ✅ Yes    | Array of QR Code IDs or tags for which analytics will be exported. |

## Examples

### **Export Single QR Code (Excel)**

```bash theme={null}
curl -X POST "https://management.scanova.io/analytics/qr/export/?from=2025-02-01&to=2025-02-25&file_format=xlsx" \
  -H "Authorization: YOUR_API_KEY" \
  -F "filter_by=qrid" \
  -F "q=Qf94b25d768294148"
```

### **Export Multiple QR Codes (PDF)**

```bash theme={null}
curl -X POST "https://management.scanova.io/analytics/qr/export/?from=2025-02-01&to=2025-02-25&file_format=pdf" \
  -H "Authorization: YOUR_API_KEY" \
  -F "filter_by=qrid" \
  -F "q=Qf94b25d768294148" \
  -F "q=Qf94b25d768294149" \
  -F "q=Qf94b25d768294150"
```

### **Export with Date Range**

```bash theme={null}
curl -X POST "https://management.scanova.io/analytics/qr/export/?from=2025-01-01&to=2025-01-31&file_format=xlsx" \
  -H "Authorization: YOUR_API_KEY" \
  -F "filter_by=qrid" \
  -F "q=Qf94b25d768294148"
```

### **Export by Tags**

```bash theme={null}
curl -X POST "https://management.scanova.io/analytics/qr/export/?from=2025-02-01&to=2025-02-25&file_format=xlsx" \
  -H "Authorization: YOUR_API_KEY" \
  -F "filter_by=tags" \
  -F "q=marketing" \
  -F "q=campaign"
```

### **Export with Bot Scans Excluded**

```bash theme={null}
curl -X POST "https://management.scanova.io/analytics/qr/export/?from=2025-02-01&to=2025-02-25&file_format=xlsx&exclude_bot_scan=true" \
  -H "Authorization: YOUR_API_KEY" \
  -F "filter_by=qrid" \
  -F "q=Qf94b25d768294148"
```

<Note>
  When `exclude_bot_scan=true`, Excel exports include an additional **Bot Scans** sheet summarising total bot hits, unique bots, top bot types, and bot activity per QR code. PDF exports include the same data as a separate section.
</Note>

## Response

### **Success Response (200 OK)**

The response returns a file download with the analytics data in the requested format.

#### **Excel File (.xlsx/.xls)**

* **Content-Type**: `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` (xlsx) or `application/vnd.ms-excel` (xls)
* **Content**: Multi-sheet Excel file with comprehensive analytics data
* **Sheets**: Multiple sheets with different analytics views

#### **PDF File (.pdf)**

* **Content-Type**: `application/pdf`
* **Content**: PDF document containing formatted analytics data
* **Structure**: Single file with all analytics data

<Note>
  The export endpoint returns a file download. Make sure your application can handle binary file responses and provide appropriate download functionality to users.
</Note>

<Info>
  Excel files (.xlsx/.xls) provide the most comprehensive data structure with multiple sheets, while PDF files ideal for sharing, printing, and presenting analytics in a visually formatted report.
</Info>

<Warning>
  Large date ranges or many QR codes may result in large file sizes. Consider breaking down exports into smaller chunks if needed.
</Warning>

## Integration Examples

### **JavaScript - Export Analytics**

```javascript theme={null}
async function exportAnalytics(filterBy, qrCodes, fromDate, toDate, format = 'xlsx') {
  try {
    const formData = new FormData();
    
    // Add filter_by
    formData.append('filter_by', filterBy);
    
    // Add QR code IDs or tags
    qrCodes.forEach(qrId => {
      formData.append('q', qrId);
    });
    
    const response = await fetch(
      `https://management.scanova.io/analytics/qr/export/?from=${fromDate}&to=${toDate}&file_format=${format}`,
      {
        method: 'POST',
        headers: {
          'Authorization': 'YOUR_API_KEY'
        },
        body: formData
      }
    );
    
    if (response.ok) {
      // Get the file blob
      const blob = await response.blob();
      
      // Create download link
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `analytics_${fromDate}_to_${toDate}.${format}`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      
      console.log('Analytics exported successfully');
      return true;
    } else {
      throw new Error('Failed to export analytics');
    }
  } catch (error) {
    console.error('Error exporting analytics:', error);
    return false;
  }
}

// Usage - Export by QR IDs
const qrCodes = ['Qf94b25d768294148', 'Qf94b25d768294149'];
exportAnalytics('qrid', qrCodes, '2025-02-01', '2025-02-25', 'xlsx');

// Usage - Export by tags
const tags = ['marketing', 'campaign'];
exportAnalytics('tags', tags, '2025-02-01', '2025-02-25', 'pdf');
```

### **Python - Export Analytics**

```python theme={null}
import requests
from datetime import datetime, timedelta

def export_analytics(filter_by, qr_codes, from_date, to_date, file_format='xlsx'):
    url = "https://management.scanova.io/analytics/qr/export/"
    headers = {"Authorization": "YOUR_API_KEY"}
    
    # Prepare form data - use list of tuples for multiple values with same key
    data = [('filter_by', filter_by)]
    for qr_id in qr_codes:
        data.append(('q', qr_id))
    
    # Prepare query parameters
    params = {
        'from': from_date,
        'to': to_date,
        'file_format': file_format
    }
    
    try:
        response = requests.post(url, headers=headers, data=data, params=params)
        response.raise_for_status()
        
        # Save the file
        filename = f"analytics_{from_date}_to_{to_date}.{file_format}"
        with open(filename, 'wb') as f:
            f.write(response.content)
        
        print(f"Analytics exported successfully to {filename}")
        return filename
        
    except requests.exceptions.RequestException as e:
        print(f"Error exporting analytics: {e}")
        return None

def export_monthly_analytics(filter_by, qr_codes, year, month):
    """Export analytics for a specific month"""
    from_date = f"{year}-{month:02d}-01"
    
    # Calculate last day of month
    if month == 12:
        next_month = datetime(year + 1, 1, 1)
    else:
        next_month = datetime(year, month + 1, 1)
    
    to_date = (next_month - timedelta(days=1)).strftime('%Y-%m-%d')
    
    return export_analytics(filter_by, qr_codes, from_date, to_date, 'xlsx')

# Usage - Export by QR IDs
qr_codes = ['Qf94b25d768294148', 'Qf94b25d768294149']
export_analytics('qrid', qr_codes, '2025-02-01', '2025-02-25', 'xlsx')

# Usage - Export by tags
tags = ['marketing', 'campaign']
export_analytics('tags', tags, '2025-02-01', '2025-02-25', 'pdf')

# Export monthly data
export_monthly_analytics('qrid', qr_codes, 2025, 2)
```

### **PHP - Export Analytics**

```php theme={null}
<?php
function exportAnalytics($filterBy, $qrCodes, $fromDate, $toDate, $fileFormat = 'xlsx') {
    $url = "https://management.scanova.io/analytics/qr/export/";
    $headers = [
        "Authorization: YOUR_API_KEY"
    ];
    
    // Prepare form data
    $data = [
        ['name' => 'filter_by', 'contents' => $filterBy]
    ];
    foreach ($qrCodes as $qrId) {
        $data[] = ['name' => 'q', 'contents' => $qrId];
    }
    
    // Prepare query parameters
    $params = http_build_query([
        'from' => $fromDate,
        'to' => $toDate,
        'file_format' => $fileFormat
    ]);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        $filename = "analytics_{$fromDate}_to_{$toDate}.{$fileFormat}";
        file_put_contents($filename, $response);
        echo "Analytics exported successfully to {$filename}";
        return $filename;
    } else {
        echo "Error exporting analytics: " . $response;
        return null;
    }
}

// Usage - Export by QR IDs
$qrCodes = ['Qf94b25d768294148', 'Qf94b25d768294149'];
$filename = exportAnalytics('qrid', $qrCodes, '2025-02-01', '2025-02-25', 'xlsx');

// Usage - Export by tags
$tags = ['marketing', 'campaign'];
$filename = exportAnalytics('tags', $tags, '2025-02-01', '2025-02-25', 'pdf');
?>
```

## Notes

* ✅ **Supports bulk analytics export** for multiple QR codes at once.
* ⚙️ **Recommended file format:**
  * `.xlsx` for visualization/reporting
  * `.pdf` for presentation, sharing, or archival purposes
* 📅 Data range can span multiple months, depending on account plan limits.
* ⏱️ Large exports may take a few seconds to generate — consider background processing for high-volume requests.

## Example Use Cases

* 📊 Generate **weekly or monthly QR scan reports**
* 🧾 Export **data for BI tools** such as Power BI or Tableau
* 📈 Analyze **trends by device, OS, or location** in Excel
* 🔍 Audit **campaign performance** across multiple QR codes

<Note />


## OpenAPI

````yaml POST /analytics/qr/export/
openapi: 3.0.0
info:
  title: Scanova API - Analytics
  description: >-
    Analytics endpoints for retrieving QR code scan data, statistics, and
    exporting analytics reports. These endpoints provide comprehensive insights
    into QR code performance, user behavior, and geographic distribution.
  version: 1.0.0
servers:
  - url: https://management.scanova.io
    description: Scanova Management API Server
security:
  - apiKeyAuth: []
paths:
  /analytics/qr/export/:
    post:
      tags:
        - Analytics
      summary: Export Analytics Data
      description: >-
        Export analytics data for specific QR codes in Excel (xls/xlsx) or CSV
        format. This endpoint allows you to download comprehensive analytics
        reports for further analysis.
      parameters:
        - name: from
          in: query
          required: true
          description: 'Start date for analytics data (inclusive). Format: YYYY-MM-DD'
          schema:
            type: string
            format: date
          example: '2025-02-01'
        - name: to
          in: query
          required: true
          description: >-
            End date for analytics data (inclusive). Format: YYYY-MM-DD.
            Defaults to current date.
          schema:
            type: string
            format: date
          example: '2025-02-25'
        - name: file_format
          in: query
          required: true
          description: Export file format
          schema:
            type: string
            enum:
              - xls
              - xlsx
              - csv
          example: xlsx
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - filter_by
                - q
              properties:
                filter_by:
                  type: string
                  enum:
                    - qrid
                    - tags
                  description: Filter by QR code ID or tags
                  example: qrid
                q:
                  type: array
                  items:
                    type: string
                  description: >-
                    Array of QR code IDs (if filter_by is 'qrid') or tags (if
                    filter_by is 'tags') to include in the export
                  example:
                    - Qf94b25d768294148
            examples:
              single_qr_code:
                summary: Export single QR code analytics
                value:
                  filter_by: qrid
                  q:
                    - Qf94b25d768294148
              multiple_qr_codes:
                summary: Export multiple QR codes analytics
                value:
                  filter_by: qrid
                  q:
                    - Qf94b25d768294148
                    - Qf94b25d768294149
                    - Qf94b25d768294150
              export_by_tags:
                summary: Export analytics by tags
                value:
                  filter_by: tags
                  q:
                    - marketing
                    - campaign
      responses:
        '200':
          description: Analytics data exported successfully
          content:
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
              schema:
                type: string
                format: binary
            application/vnd.ms-excel:
              schema:
                type: string
                format: binary
            text/csv:
              schema:
                type: string
                format: binary
        '400':
          description: Bad request - Invalid parameters
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Invalid parameters
                  message:
                    type: string
                    example: Required parameters are missing or invalid
        '401':
          description: Unauthorized - Invalid API key
          content:
            application/json:
              schema:
                type: object
                properties:
                  detail:
                    type: string
                    example: Authentication credentials were not provided.
      security:
        - apiKeyAuth: []
components:
  securitySchemes:
    apiKeyAuth:
      type: apiKey
      in: header
      name: Authorization
      description: >-
        API key authentication. Enter your API key directly in the Authorization
        header.

````