98 lines
3.3 KiB
Python
98 lines
3.3 KiB
Python
import csv
|
|
import io
|
|
import re
|
|
import zipfile
|
|
import xml.etree.ElementTree as ET
|
|
|
|
|
|
class XLSXReader:
|
|
def read(self, data):
|
|
rows = []
|
|
try:
|
|
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
|
shared_strings = self._parse_shared_strings(z)
|
|
sheet_data = self._parse_sheet(z, shared_strings)
|
|
if sheet_data:
|
|
rows = self._rows_from_sheet_data(sheet_data)
|
|
except Exception:
|
|
raise ValueError('无法解析 xlsx 文件,请确认文件格式正确')
|
|
return rows
|
|
|
|
def _parse_shared_strings(self, z):
|
|
strings = {}
|
|
try:
|
|
xml_data = z.read('xl/sharedStrings.xml')
|
|
root = ET.fromstring(xml_data)
|
|
ns = {'s': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
|
|
for i, si in enumerate(root.findall('.//s:si', ns)):
|
|
text_parts = []
|
|
for t in si.findall('.//s:t', ns):
|
|
if t.text:
|
|
text_parts.append(t.text)
|
|
strings[i] = ''.join(text_parts)
|
|
except KeyError:
|
|
pass
|
|
return strings
|
|
|
|
def _parse_sheet(self, z, shared_strings):
|
|
cells = {}
|
|
try:
|
|
xml_data = z.read('xl/worksheets/sheet1.xml')
|
|
root = ET.fromstring(xml_data)
|
|
ns = {'s': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
|
|
'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'}
|
|
for row in root.findall('.//s:row', ns):
|
|
row_num = int(row.get('r', 0))
|
|
for c in row.findall('s:c', ns):
|
|
ref = c.get('r', '')
|
|
col_letter = re.match(r'([A-Z]+)', ref).group(1) if ref else ''
|
|
col_idx = self._col_to_index(col_letter)
|
|
value_type = c.get('t', '')
|
|
value_elem = c.find('s:v', ns)
|
|
raw_value = value_elem.text if value_elem is not None else ''
|
|
if value_type == 's' and raw_value:
|
|
value = shared_strings.get(int(raw_value), raw_value)
|
|
else:
|
|
value = raw_value
|
|
cells[(row_num, col_idx)] = value
|
|
except KeyError:
|
|
pass
|
|
return cells
|
|
|
|
def _col_to_index(self, col):
|
|
index = 0
|
|
for c in col:
|
|
index = index * 26 + (ord(c) - ord('A') + 1)
|
|
return index - 1
|
|
|
|
def _rows_from_sheet_data(self, cells):
|
|
if not cells:
|
|
return []
|
|
max_row = max(r for r, _ in cells.keys())
|
|
max_col = max(c for _, c in cells.keys())
|
|
rows = []
|
|
for r in range(1, max_row + 1):
|
|
row = []
|
|
for c in range(max_col + 1):
|
|
row.append(cells.get((r, c), ''))
|
|
if any(cell.strip() for cell in row):
|
|
rows.append(row)
|
|
return rows
|
|
|
|
|
|
class CSVReader:
|
|
def read(self, data):
|
|
text = data.decode('utf-8-sig')
|
|
reader = csv.reader(io.StringIO(text))
|
|
rows = []
|
|
for row in reader:
|
|
if any(cell.strip() for cell in row):
|
|
rows.append(row)
|
|
return rows
|
|
|
|
|
|
def parse_excel(data):
|
|
if data[:2] == b'PK':
|
|
return XLSXReader().read(data)
|
|
else:
|
|
return CSVReader().read(data) |