Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(surveys): include emails and format excel exports (#102487)

Lucas Faria9a4b644cd8b0
diff --git a/docs/internal/survey-responses.md b/docs/internal/survey-responses.md
index 75d8eb5f3e00..f897500640d9 100644
--- a/docs/internal/survey-responses.md
+++ b/docs/internal/survey-responses.md
@@ -25,8 +25,14 @@ The Responses tab has an export control in the table.
The same export remains available in the action sidebar.
CSV and Excel downloads from all three locations use the same format.
-Each row contains a respondent ID, a UTC submission timestamp, response status, and one column per answerable question.
+Each row contains a respondent ID, email when available, a UTC submission timestamp, response status, and one column per answerable question.
+Email comes from the person's `$email` property, falling back to `email` when `$email` is empty.
+Responses without an email retain their respondent ID and have a blank email cell.
Question headings include their position and full text, so repeated questions remain distinct.
Link questions are omitted, multiple-choice answers are comma-separated, and two-point ratings use **Thumbs up** or **Thumbs down**.
Unanswered questions have blank cells.
Downloads exclude the internal response payload and table action column.
+
+Excel downloads include bold, wrapped headings, readable column widths, wrapped answers, column filters, and a frozen header row.
+Row heights expand for multiline answers up to Excel's row-height limit; longer answers remain available in the cell.
+These layout settings also apply to other tabular Excel downloads through the shared exporter.
diff --git a/frontend/src/scenes/surveys/utils.test.ts b/frontend/src/scenes/surveys/utils.test.ts
index cea2d9b02644..4da613eeb711 100644
--- a/frontend/src/scenes/surveys/utils.test.ts
+++ b/frontend/src/scenes/surveys/utils.test.ts
@@ -84,6 +84,7 @@ describe('survey utils', () => {
expect(query.columns).toEqual([
'Respondent ID',
+ 'Email',
'Submitted at (UTC)',
'Status',
'Q1: What worked? What could improve?',
@@ -101,7 +102,10 @@ describe('survey utils', () => {
expect(sql).toContain('AND timestamp >= now() - INTERVAL 7 DAY')
expect(sql).toContain("HAVING uuid NOT IN ('archived-response')")
expect(sql).not.toMatch(/AS response\b|AS actions\b|AS answer_\d|LIMIT 100/)
- expect(sql.split(' FROM (')[0]).not.toMatch(/person_properties|event_properties/)
+ expect(sql).toContain(
+ "coalesce(nullIf(JSONExtractString(person_properties, '$email'), ''), nullIf(JSONExtractString(person_properties, 'email'), ''), '') AS Email"
+ )
+ expect(sql.split(' FROM (')[0]).not.toMatch(/person_properties AS|event_properties/)
})
it.each([
diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.ts
index d145ce3c25ce..b31bd5e6208d 100644
--- a/frontend/src/scenes/surveys/utils.ts
+++ b/frontend/src/scenes/surveys/utils.ts
@@ -920,9 +920,10 @@ export function buildSurveyResponsesExportQuery(
): DataTableNode & { source: HogQLQuery } {
const questions = getAnswerableQuestions(survey)
const merged = buildMergedSubmissionsSubquery(survey, filters, questions, { includeRespondentMetadata: true })
- const columns = ['Respondent ID', 'Submitted at (UTC)', 'Status']
+ const columns = ['Respondent ID', 'Email', 'Submitted at (UTC)', 'Status']
const expressions = [
'distinct_id',
+ "coalesce(nullIf(JSONExtractString(person_properties, '$email'), ''), nullIf(JSONExtractString(person_properties, 'email'), ''), '')",
"formatDateTime(submitted_at, '%Y-%m-%d %H:%i:%S', 'UTC')",
"multiIf(outcome = 'completed', 'Completed', outcome = 'dismissed', 'Dismissed', 'Abandoned')",
]
diff --git a/products/exports/backend/tasks/csv_exporter.py b/products/exports/backend/tasks/csv_exporter.py
index f419938fb083..1861b93d60b6 100644
--- a/products/exports/backend/tasks/csv_exporter.py
+++ b/products/exports/backend/tasks/csv_exporter.py
@@ -3,6 +3,7 @@ import csv
import json
import datetime
import tempfile
+import textwrap
from collections import OrderedDict
from collections.abc import Generator, Iterator
from contextlib import contextmanager
@@ -15,7 +16,9 @@ from django.http import QueryDict
import requests
import structlog
from openpyxl import Workbook
-from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
+from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE, WriteOnlyCell
+from openpyxl.styles import Alignment, Font, PatternFill
+from openpyxl.utils import get_column_letter
from pydantic import BaseModel, ValidationError
from requests.exceptions import HTTPError
from rest_framework_csv.renderers import CSVRenderer
@@ -93,11 +96,47 @@ class ExcelWriter(TabularWriter):
self._workbook = Workbook(write_only=True)
self._worksheet = self._workbook.create_sheet()
self._columns: list[str] = []
+ self._column_widths: list[int] = []
+ self._row_count = 0
+ self._alignment = Alignment(wrap_text=True, vertical="top")
+ self._header_font = Font(bold=True)
+ self._header_fill = PatternFill(fill_type="solid", fgColor="EDEDED")
+
+ def _append_row(self, values: list[str | int | float | bool | None], *, header: bool = False) -> None:
+ cells = []
+ line_count = 1
+ max_lines = 27
+ for value, width in zip(values, self._column_widths):
+ cell = WriteOnlyCell(self._worksheet, value=value)
+ cell.alignment = self._alignment
+ if header:
+ cell.font = self._header_font
+ cell.fill = self._header_fill
+ cells.append(cell)
+ if isinstance(value, str) and line_count < max_lines:
+ if len(value) > width * max_lines:
+ line_count = max_lines
+ else:
+ line_count = min(
+ max_lines,
+ max(
+ line_count,
+ sum(max(1, len(textwrap.wrap(line, width=width - 2))) for line in value.splitlines()),
+ ),
+ )
+ self._row_count += 1
+ self._worksheet.row_dimensions[self._row_count].height = min(409, 15 * line_count + 6)
+ self._worksheet.append(cells)
+ del self._worksheet.row_dimensions[self._row_count]
def write_header(self, columns: list[str]) -> None:
self._columns = columns
try:
- self._worksheet.append([sanitize_formula_injection(c) for c in columns])
+ self._column_widths = [min(60, max(28, len(c) + 2)) for c in columns]
+ self._worksheet.freeze_panes = "A2"
+ for index, width in enumerate(self._column_widths, start=1):
+ self._worksheet.column_dimensions[get_column_letter(index)].width = width
+ self._append_row([sanitize_formula_injection(sanitize_value_for_excel(c)) for c in columns], header=True)
except ValueError as e:
if "Invalid column index" in str(e):
raise ExcelColumnLimitExceeded() from e
@@ -114,13 +153,15 @@ class ExcelWriter(TabularWriter):
value = sanitize_formula_injection(value)
values.append(value)
try:
- self._worksheet.append(values)
+ self._append_row(values)
except ValueError as e:
if "Invalid column index" in str(e):
raise ExcelColumnLimitExceeded() from e
raise
def finish(self) -> str:
+ if self._columns:
+ self._worksheet.auto_filter.ref = f"A1:{get_column_letter(len(self._columns))}{self._row_count}"
self._workbook.save(self._path)
return self._path
diff --git a/products/exports/backend/tasks/test/test_csv_exporter.py b/products/exports/backend/tasks/test/test_csv_exporter.py
index ef5d70b622a0..1551a3cddd98 100644
--- a/products/exports/backend/tasks/test/test_csv_exporter.py
+++ b/products/exports/backend/tasks/test/test_csv_exporter.py
@@ -1756,6 +1756,8 @@ class TestCSVExporter(APIBaseTest):
assert _format_breakdown_value(["a", "b", "c"]) == "a::b::c"
assert _format_breakdown_value(["single"]) == "single"
+
+class TestExcelWriter:
def test_excel_writer_raises_column_limit_exceeded(self) -> None:
writer = ExcelWriter()
# Create more columns than openpyxl supports (18,278 max)
@@ -1768,15 +1770,37 @@ class TestCSVExporter(APIBaseTest):
assert "18,278 columns" in str(exc_info.value)
assert "CSV format" in str(exc_info.value)
- def test_excel_writer_normal_column_count_works(self) -> None:
+ @pytest.mark.parametrize(
+ "answer",
+ [
+ 'Please keep the "weekly" filter.\n' + "Long responses should wrap without widening every column. " * 8,
+ "Long answer.\n" * 2000,
+ "x" * 32767,
+ ],
+ )
+ def test_excel_writer_formats_readable_rows(self, answer: str) -> None:
writer = ExcelWriter()
- columns = ["col_a", "col_b", "col_c"]
+ columns = ["Respondent ID", "Email", "Q1: What could we improve about the report builder?"]
writer.write_header(columns)
- writer.write_row({"col_a": "1", "col_b": "2", "col_c": "3"})
+ writer.write_row(dict(zip(columns, ["anonymous-1", None, answer])))
path = writer.finish()
-
- assert os.path.exists(path)
- os.unlink(path)
+ try:
+ workbook = load_workbook(path)
+ sheet = workbook.active
+ assert list(sheet.values) == [tuple(columns), ("anonymous-1", None, answer)]
+ assert sheet.freeze_panes == "A2"
+ assert sheet.auto_filter.ref == "A1:C2"
+ assert sheet["C1"].font.bold
+ assert sheet["C1"].alignment.wrap_text
+ assert sheet["C2"].alignment.wrap_text
+ assert sheet["C2"].alignment.vertical == "top"
+ assert 24 <= sheet.column_dimensions["C"].width <= 60
+ assert sheet.row_dimensions[2].height > sheet.sheet_format.defaultRowHeight
+ assert sheet.row_dimensions[2].height <= 409
+ if len(answer) > 2000:
+ assert sheet.row_dimensions[2].height == 409
+ finally:
+ os.unlink(path)
@override_settings(SITE_URL="http://testserver")