在使用Python寫入數據到Excel表格中時出現報錯信息記錄:“NotImplementedError: formatting_info=True not yet implemented”
報錯分析:看報錯信息是未實現的錯,其實就是版本不兼容
我在代碼中寫的是使用xlrd庫的方法進行Excel處理,但是我創建的Excel是office 2016版本的,而xlrd只支持2007以前的版本,導致不兼容報錯
解決辦法1:將模板文件另存為Excel 2003版本的文件格式
解決方法2:使用Python的openpyxl庫中的方法進行編寫代碼
xlrd庫與openpyxl庫中使用的一些方法說明:
(1)、打開一個Excel文件
xlrd中用open_workbook方法:
def open_workbook(filename=None, logfile=sys.stdout, verbosity=0, use_mmap=USE_MMAP, file_contents=None, encoding_override=None, formatting_info=False, on_demand=False, ragged_rows=False):
open_workbook方法中參數說明:
- filename參數:是要打開文件的路徑及名稱
- logfile:寫入消息和診斷的打開文件
- verbosity:增加寫入的日志文件
- use_mmap:是否使用mmap模塊是用啟發式方法,如果存在,則使用mmap
- file_contents:使用了該參數就不要使用filename
- formatting_info:默認值是“False”,當“True”時,格式信息將從電子表格中讀取文件。
- ragged_rows:默認值“False”表示所有行都用空單元格填充,“True” 表示行的末尾沒有空單元格。
openpyxl中用load_workbook方法:
def load_workbook(filename, read_only=False, keep_vba=KEEP_VBA, data_only=False, keep_links=True)
load_workbook方法中的參數說明:
- filename:打開文件的路徑或對象
- read_only:為讀取而優化,內容無法編輯,false時可以編輯,true時無法編輯
- keep_vba:保留vba內容
- data_only:控制帶有公式的單元格是具有公式(默認值)還是具有上次Excel讀取工作表時存儲的值
- keep_links:是否應保留指向外部工作簿的鏈接。默認值為True
(2)、復制一個文件都用copy,保存文件都用save
(3)、添加一個sheet工作表
xlrd中用add_sheet方法:
def add_sheet(self, sheetname, cell_overwrite_ok=False):
add_sheet方法參數說明:
- sheetname:工作表的名稱
- cell_overwrite_ok:默認是false,如果是“True”,則添加的工作表中的單元格將不會因為多次寫入時出現異常。
openpyxl中用create_sheet方法:
def create_sheet(self, title=None, index=None):
create_sheet方法中的參數說明,就兩個參數:
- title:插入工作表的名稱,str類型
- index:從第幾個開始插入,索引從0開始
(4)、寫入數據到Excel表格中
xlrd中用write方法:
def write(self, r, c, label="", style=Style.default_style):
write方法參數說明:
- r參數:寫入的行
- c參數:寫入的列
- label:要寫入的數據值
- style:寫入的樣式
openpyxl中用cell方法:
def cell(self, row, column, value=None):
cell方法參數說明:
- row:寫入單元格的行
- column:寫入單元格的列
- value:寫入單元格的值
最后貼上兩種不同庫寫入Excel數據的代碼:
(1)使用Python的xlrd庫實現導出數據到Excel中
def export_excel(self, names_export): """ :param names_export: :param name_export: 待導出的接口名稱,列表形式 :return: """ counts_export = len(names_export) # 導出總數 fail_export = [] # 導出失敗接口名列表 try: src = open_workbook(config.src_path+'/report/report_module.xls', formatting_info=True) destination = copy(src) dt = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # 當前時間戳 file_path = config.src_path+'/report/'+str(dt)+'.xls' destination.save(file_path) # 保存模板表格到新的目錄下 for name_interface in names_export: case_interface = operation_db.select_all("select * from case_interface where case_status=1 and " "name_interface='%s'" % name_interface) if len(case_interface['data']) != 0 and case_interface['code'] == '0000': src = open_workbook(file_path, formatting_info=True) destination = copy(src) sheet = destination.add_sheet(name_interface, cell_overwrite_ok=True) for col in range(0, len(self.field)): sheet.write(0, col, self.field[col]) # 獲取並寫數據段信息到sheet中 for row in range(1, len(case_interface['data'])+1): for col in range(0, len(self.field)): sheet.write(row, col, '%s' % case_interface['data'][row-1][col]) # 寫數據到對應的Excel表中 destination.save(file_path) elif len(case_interface['data']) == 0 and case_interface['code'] == '0000': fail_export.append(name_interface) else: fail_export.append(name_interface) result = {'code': '0000', 'message': '導出總數%s,失敗數:%s' % (counts_export, len(fail_export)), 'data': fail_export} except Exception as e: result = {'code': '9999', 'message': '導出過程異常|導出總數:%s,失敗數:%s' % (counts_export, len(fail_export)), 'data': fail_export} logging.basicConfig(filename=config.src_path+'/log/syserror.log', level=logging.DEBUG, format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s') logger = logging.getLogger(__name__) logger.exception(e) return result
(2)使用Python的openpyxl庫中的方法實現寫入數據到Excel中
def export_excel(self, names_export): """ :param names_export: :param name_export: 待導出的接口名稱,列表形式 :return: """ counts_export = len(names_export) # 導出總數 fail_export = [] # 導出失敗接口名列表 try: # src = open_workbook(config.src_path+'/report/report_module.xls', formatting_info=True) src = load_workbook(config.src_path + '/report/report_module.xlsx', read_only=False) destination = copy(src) dt = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # 當前時間戳 file_path = config.src_path+'/report/'+str(dt)+'.xlsx' destination.save(file_path) # 保存模板表格到新的目錄下 for name_interface in names_export: case_interface = operation_db.select_all("select * from case_interface where case_status=1 and " "name_interface='%s'" % name_interface) if len(case_interface['data']) != 0 and case_interface['code'] == '0000': src = load_workbook(file_path, read_only=False) destination = copy(src) sheet = destination.create_sheet(name_interface, 0) for col in range(1, len(self.field)+1): sheet.cell(1, col, self.field[col-1]) # 獲取並寫數據段信息到sheet中 for row in range(2, len(case_interface['data'])+2): for col in range(1, len(self.field)+1): sheet.cell(row, col, '%s' % case_interface['data'][row-2][col-1]) # 寫數據到對應的Excel表中 destination.save(file_path) elif len(case_interface['data']) == 0 and case_interface['code'] == '0000': fail_export.append(name_interface) else: fail_export.append(name_interface) result = {'code': '0000', 'message': '導出總數%s,失敗數:%s' % (counts_export, len(fail_export)), 'data': fail_export} except Exception as e: result = {'code': '9999', 'message': '導出過程異常|導出總數:%s,失敗數:%s' % (counts_export, len(fail_export)), 'data': fail_export} logging.basicConfig(filename=config.src_path+'/log/syserror.log', level=logging.DEBUG, format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s') logger = logging.getLogger(__name__) logger.exception(e) return result