# coding: utf-8
import os
import xlwt
import xlrd
class ExcelProcess():
def __init__(self, file_path, file_name):
self.file_path = file_path
self.file_name = file_name
self.file = os.path.join(self.file_path, self.file_name)
self.workbook = ""
self.sheet = ""
def _exec_file(self, action='r', **kwargs):
if action == 'r':
self.workbook = xlrd.open_workbook(self.file, **kwargs)
else:
self.workbook = xlwt.Workbook(encoding='utf-8')
def _exec_sheet(self, action='r', sheet="", cell_overwrite_ok=False):
if action == 'r':
try:
self.sheet = self.workbook.sheet_by_index(sheet)
except Exception: # pylint: disable=broad-except
self.sheet = self.workbook.sheet_by_name(sheet)
else:
self.sheet = self.workbook.add_sheet(sheet, cell_overwrite_ok=cell_overwrite_ok)
def _save(self):
if not os.path.isdir(self.file_path):
os.makedirs(self.file_path)
self.workbook.save(self.file.encode('utf-8'))
return False if not os.path.isfile(self.file) else True
def read_header(self):
return self.sheet.row_values(0)
def read_sheet_data(self):
rows = self.sheet.nrows
data = [self.sheet.row_values(i + 1) for i in range(0, rows - 1)]
return data
def import_file(self, sheet_name, **kwargs):
self._exec_file('r', **kwargs)
self._exec_sheet(sheet=sheet_name)
return self.read_header(), self.read_sheet_data()
def write_header(self, header):
for index, value in enumerate(header):
self.sheet.write(0, index, label=value)
def write_sheet_data(self, data):
for row in range(0, len(data)):
for col in range(0, len(data[0])):
self.sheet.write(row + 1, col, label=data[row][col])
def export_header_file(self, header_format, sheet_name):
self._exec_file('w')
self._exec_sheet('w', sheet_name)
self.write_header(header_format)
return self._save()
def export_file(self, sheet_name, header, data, cell_overwrite_ok=False, multi_sheet=False, auto_save=True):
if multi_sheet is False:
self._exec_file('w')
self._exec_sheet('w', sheet_name, cell_overwrite_ok=cell_overwrite_ok)
self.write_header(header)
self.write_sheet_data(data)
if auto_save:
self._save()
workbook = ExcelProcess('./', 'nuclei_tmplate.xlsx')
sheet_content = workbook.import_file(0)
label_list = []
for item in sheet_content[1]:
label_list.extend([i for i in item[3].split(',') if i])
最新的xlrd不支持?xlsx文件的读取,需要安装下面的版本
pip install xlrd==1.2.0
|