Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Export to CSV with UTF-8 encoding #826

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/vanna/base/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2099,3 +2099,43 @@ def get_plotly_figure(
fig.update_layout(template="plotly_dark")

return fig

def export_to_csv(self, df: pd.DataFrame, filepath: str, **kwargs) -> None:
"""
Example:
```python
vn.export_to_csv(df, "results.csv")
```

Export a pandas DataFrame to a CSV file with proper UTF-8 encoding.
This ensures that non-ASCII text(such as Chinese characters) are correctly rendered in the exported file.

Args:
df (pd.DataFrame): The DataFrame to export to CSV.
filepath (str): The file path where the CSV will be saved.
**kwargs: Additional keyword arguments to pass to pandas' to_csv method.

Returns:
None
"""
if not isinstance(df, pd.DataFrame):
raise TypeError("Expected pandas DataFrame")
if not isinstance(filepath, str):
raise TypeError("Filepath must be string")

# Set default encoding to UTF-8 if not provided
if 'encoding' not in kwargs:
kwargs['encoding'] = 'utf-8'

# Set default index parameter to False if not provided
if 'index' not in kwargs:
kwargs['index'] = False

try:
df.to_csv(filepath, **kwargs)
except OSError as e:
self.log(f"File system error: {e}", title="Export Error")
raise
except pd.errors.PandasError as e:
self.log(f"Data export error: {e}", title="Export Error")
raise