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

Fix xlsx file support #67

Merged
merged 6 commits into from
Oct 26, 2020
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@
## Current (in progress)

- Protect custom type testers against None values [#66](https://github.com/etalab/csvapi/pull/66)
- Fix xlsx file support [#67](https://github.com/etalab/csvapi/pull/67)

## 1.0.3 (2020-03-04)

20 changes: 14 additions & 6 deletions csvapi/parser.py
Original file line number Diff line number Diff line change
@@ -10,9 +10,9 @@
SNIFF_LIMIT = 4096


def is_binary(filepath):
with os.popen('file {} -b --mime-type'.format(filepath)) as proc:
return 'text/plain' not in proc.read().lower()
def detect_type(filepath):
with os.popen(f'file {filepath} -b --mime-type') as proc:
return proc.read().lower()


def detect_encoding(filepath):
@@ -28,8 +28,11 @@ def from_csv(filepath, encoding='utf-8', sniff_limit=SNIFF_LIMIT):
return agate.Table.from_csv(filepath, encoding=encoding, column_types=agate_tester())


def from_excel(filepath):
def from_excel(filepath, xlsx=False):
# Function exists to prevent side-effects after monckey patching with import
import agateexcel # noqa
if xlsx:
return agate.Table.from_xlsx(filepath, column_types=agate_tester())
return agate.Table.from_xls(filepath, column_types=agate_tester())


@@ -39,9 +42,14 @@ def to_sql(table, urlhash, storage):


def parse(filepath, urlhash, storage, encoding=None, sniff_limit=SNIFF_LIMIT):
if is_binary(filepath):
file_type = detect_type(filepath)
if 'application/vnd.ms-excel' in file_type:
table = from_excel(filepath)
else:
elif 'application/vnd.openxml' in file_type:
table = from_excel(filepath, xlsx=True)
elif 'text/plain' in file_type:
encoding = detect_encoding(filepath) if not encoding else encoding
table = from_csv(filepath, encoding=encoding, sniff_limit=sniff_limit)
else:
raise Exception(f'Unsupported file type {file_type}')
return to_sql(table, urlhash, storage)