Created
September 1, 2021 07:03
-
-
Save qi7chen/ad9e363c0c3cc2716ad59c01f0501e13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import xlrd | |
import openpyxl | |
# 读取指定xls文件的某一个sheet | |
def read_workbook_sheet_to_rows(filename: str, sheet_name: str): | |
print('load workbook', filename) | |
if filename.endswith('.xls'): | |
return __xlrd_read_workbook_sheet_to_rows(filename, sheet_name) | |
elif filename.endswith('.xlsx'): | |
return __openpyxl_read_workbook_sheet_to_rows(filename, sheet_name) | |
else: | |
raise RuntimeError('file %s extension not recognized' % filename) | |
# 读取.xls | |
def __xlrd_read_workbook_sheet_to_rows(filename: str, sheet_name: str): | |
book = xlrd.open_workbook(filename, on_demand=True) | |
sheet = book.sheet_by_name(sheet_name) | |
rows = [] | |
for rx in range(sheet.nrows): | |
row = sheet.row(rx) | |
new_row = [] | |
for cell in row: | |
new_row.append(str(cell.value)) | |
rows.append(new_row) | |
return rows | |
# 读取.xlsx | |
def __openpyxl_read_workbook_sheet_to_rows(filename: str, sheet_name: str): | |
print('load workbook', filename) | |
wb = openpyxl.load_workbook(filename, data_only=True, read_only=True) | |
sheet = wb.get_sheet_by_name(sheet_name) | |
rows = [] | |
assert sheet is not None, sheet_name | |
for i, sheet_row in enumerate(sheet.rows): | |
row = [] | |
for j, cell in enumerate(sheet_row): | |
text = '' | |
if cell.value is not None: | |
text = str(cell.value) | |
row.append(text.strip()) | |
rows.append(row) | |
wb.close() | |
return rows |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment