1. 程式人生 > >Python匯出資料到Excel表格-NotImplementedError: formatting_info=True not yet implemented

Python匯出資料到Excel表格-NotImplementedError: formatting_info=True not yet implemented

在使用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

&n