{"id":47,"date":"2020-05-10T16:50:25","date_gmt":"2020-05-10T08:50:25","guid":{"rendered":"https:\/\/jiangshibo.cn\/?p=47"},"modified":"2020-12-13T22:41:11","modified_gmt":"2020-12-13T14:41:11","slug":"python-%e6%93%8d%e4%bd%9cexcel","status":"publish","type":"post","link":"https:\/\/jiangshibo.cn\/index.php\/2020\/05\/10\/python-%e6%93%8d%e4%bd%9cexcel\/","title":{"rendered":"Python \u64cd\u4f5cExcel"},"content":{"rendered":"<p><!--more--><\/p>\n<p><!-- TOC --><\/p>\n<ul>\n<li><a class=\"wp-editor-md-post-content-link\" href=\"#1-\u524d\u8a00\">1. \u524d\u8a00<\/a><\/li>\n<li><a class=\"wp-editor-md-post-content-link\" href=\"#2-\u4f7f\u7528openpyxl\">2. \u4f7f\u7528openpyxl<\/a><\/li>\n<li><a class=\"wp-editor-md-post-content-link\" href=\"#3-\u4f7f\u7528xlwings\">3. \u4f7f\u7528xlwings<\/a>\n<ul>\n<li><a class=\"wp-editor-md-post-content-link\" href=\"#31-\u5220\u9664\u884c-rangeapientirerowdelete\">3.1. \u5220\u9664\u884c: range.api.EntireRow.Delete()<\/a><\/li>\n<li><a class=\"wp-editor-md-post-content-link\" href=\"#32-\u63d2\u5165\u884c-sheetapirowsrow_numberinsert\">3.2. \u63d2\u5165\u884c: sheet.api.Rows(row_number).Insert()<\/a><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<h2><!-- \/TOC --><\/h2>\n<h1>1. \u524d\u8a00<\/h1>\n<p>\u7531\u4e8e\u8fd1\u671f\u6709\u4efb\u52a1\u9700\u8981\uff0c\u8981\u5199\u4e00\u4e2a\u80fd\u591f\u5904\u7406Excel\u7684\u811a\u672c\uff0c\u5b9e\u73b0\u7684\u529f\u80fd\u662f\uff0c\u5728A\u8868\u683c\u4e0a\u5176\u4e2d\u4e00\u5217\uff0c\u5bf9\u5b57\u7b26\u4e32\u8fdb\u884c\u5206\u7ec4\u548c\u6392\u5e8f\uff0c\u7136\u540e\u6839\u636e\u6392\u5e8f\u597d\u7684A\u8868\u683c\u4ee5\u56fa\u5b9a\u683c\u5f0f\u81ea\u52a8\u586b\u5199\u5230B\u8868\u683c\u4e0a\u3002<\/p>\n<p>\u5f00\u59cb\u5199\u811a\u672c\u4e4b\u524d\u67e5\u4e86\u5f88\u591a\u8d44\u6599\uff0c\u6700\u5f00\u59cb\u91c7\u7528\u4e86openpyxl\u8fd9\u4e2a\u6a21\u5757\uff0c\u7528\u8d77\u6765\u5f88\u987a\u624b\uff0c\u4f7f\u7528\u8fd9\u4e2a\u5bf9A\u8868\u683c\u5176\u4e2d\u4e00\u5217\u8fdb\u884c\u4e86\u91cd\u65b0\u586b\u5199\uff0c\u4f46\u662f\u540e\u6765\u53d1\u73b0\uff0c\u9700\u8981\u7528\u5230\u5220\u9664\u548c\u63d2\u5165\u7a7a\u767d\u884c\u7684\u64cd\u4f5c\uff0c\u4f7f\u7528openpyxl\u6bd4\u8f83\u56f0\u96be\uff0c\u8fd9\u4e2a\u6a21\u5757\u4ec5\u652f\u6301\u5728\u8868\u683c\u7684\u6700\u540e\u4e00\u884c\u7ee7\u7eed\u6dfb\u52a0\u65b0\u884c\uff0c\u4e0d\u652f\u6301\u5728\u4e2d\u95f4\u63d2\u5165\u548c\u5220\u9664\u884c\u3002<\/p>\n<p>\u5728\u67e5\u627e\u7684\u8fc7\u7a0b\u4e2d\u53d1\u73b0\uff0c\u7f51\u4e0a\u6d41\u4f20\u4e86\u4e00\u4e9b\u4f7f\u7528openpyxl\u8fdb\u884c\u63d2\u5165\u5220\u9664\u884c\u7684\u64cd\u4f5c\uff0c\u73b0\u6574\u7406\u4e00\u4e0b\u3002<\/p>\n<h1>2. \u4f7f\u7528openpyxl<\/h1>\n<p>\u4e00\u79cd\u601d\u8def\u662f\u5c06sheet\u6570\u636e\u8f6c\u6362\u6210list\uff0c\u7136\u540e\u5728list\u8fdb\u884c\u64cd\u4f5c\uff0c\u8fd9\u79cd\u65b9\u6cd5\u53ef\u884c\uff0c\u4f46\u662f\u5b9e\u9645\u6d4b\u8bd5\u4e4b\u540e\u53d1\u73b0\u8fd0\u884c\u8d77\u6765\u901f\u5ea6\u592a\u6162\u4e86\uff0c\u6570\u636e1000\u591a\u6761\uff0c\u65f6\u95f4\u5c31\u5df2\u7ecf\u7b49\u4e0d\u8d77\u4e86\u3002<\/p>\n<pre><code class=\"language-python \"># Creat insert row function group----------------------------------------------\ndef blankRowInsert(sheet, row_num, add_num):\n    myList = Sheet2List(sheet)\n    insertLine(myList, row_num, add_num, sheet.max_column)\n    List2Sheet(sheet,myList)\n\ndef Sheet2List(sheet):\n    # \u628a\u4e00\u4e2a\u8868\u683c\u4e2d\u7684\u6570\u636e\u5168\u90e8\u5bfc\u51fa\u5230\u4e00\u4e2a\u5217\u8868\n    listResult = []\n    for i in range(1,sheet.max_row + 1):\n        lineData = []\n        for j in range(1,sheet.max_column +1):\n            cell = sheet.cell(row = i, column = j)\n            lineData.append(cell.value)\n        listResult.append(lineData)\n    return listResult\n\ndef insertLine(aList, row_num , add_num, maxColumn):\n    # \u5bf9\u5217\u8868\u8fdb\u884c\u6dfb\u52a0\u64cd\u4f5c\u64cd\u4f5c\n    for _ in range(1,add_num + 1):\n        # ['']*N\u662f\u521b\u5efa\u4e00\u4e2a\u4e2a\u6570\u4e3aN\u7684\u7a7a\u683c\u5217\u8868\uff0c\u63d2\u5165\u5217\u8868aList\n        aList.insert(row_num, [''] * maxColumn)\n\ndef List2Sheet(sheet,list):\n    # \u628a\u6570\u636e\u5199\u56desheet\n    for i in range(1, len(list) + 1):\n        for j in range(1, len(list[0]) + 1):\n            cell = sheet.cell(row=i, column=j)\n            cell.value = list[i-1][j-1]\n# End of insert row function group---------------------------------------------\n<\/code><\/pre>\n<p>\u53e6\u5916\u4e00\u79cd\u601d\u8def\u662f\u76f4\u63a5\u81ea\u5df1\u7ed9openpyxl\u8fd9\u4e2a\u8f6e\u5b50\u8865\u80ce\uff0c\u6dfb\u52a0\u4e00\u4e2a\u65b0\u7684\u65b9\u6cd5\uff0c\u7b14\u8005\u6ca1\u6709\u8bd5\u9a8c\uff0c\u4e0b\u9762\u7684\u4ee3\u7801\u662fStackOverflow\u76f8\u5173\u95ee\u9898\u4e0a\u9762\u8d34\u7684\uff0c\u5982\u679c\u5404\u4f4d\u6709\u5174\u8da3\u53ef\u4ee5\u81ea\u5df1\u5c1d\u8bd5\u3002<\/p>\n<pre><code class=\"language-python \">def insert_rows(self, row_idx, cnt, above=False, copy_style=True, fill_formulae=True):\n    \"\"\"Inserts new (empty) rows into worksheet at specified row index.\n\n    :param row_idx: Row index specifying where to insert new rows.\n    :param cnt: Number of rows to insert.\n    :param above: Set True to insert rows above specified row index.\n    :param copy_style: Set True if new rows should copy style of immediately above row.\n    :param fill_formulae: Set True if new rows should take on formula from immediately above row, filled with references new to rows.\n\n    Usage:\n\n    * insert_rows(2, 10, above=True, copy_style=False)\n\n    \"\"\"\n    CELL_RE  = re.compile(\"(?P&lt;col&gt;\\$?[A-Z]+)(?P&lt;row&gt;\\$?\\d+)\")\n\n    row_idx = row_idx - 1 if above else row_idx\n\n    def replace(m):\n        row = m.group('row')\n        prefix = \"$\" if row.find(\"$\") != -1 else \"\"\n        row = int(row.replace(\"$\",\"\"))\n        row += cnt if row &gt; row_idx else 0\n        return m.group('col') + prefix + str(row)\n\n    # First, we shift all cells down cnt rows...\n    old_cells = set()\n    old_fas   = set()\n    new_cells = dict()\n    new_fas   = dict()\n    for c in self._cells.values():\n\n        old_coor = c.coordinate\n\n        # Shift all references to anything below row_idx\n        if c.data_type == Cell.TYPE_FORMULA:\n            c.value = CELL_RE.sub(\n                replace,\n                c.value\n            )\n            # Here, we need to properly update the formula references to reflect new row indices\n            if old_coor in self.formula_attributes and 'ref' in self.formula_attributes[old_coor]:\n                self.formula_attributes[old_coor]['ref'] = CELL_RE.sub(\n                    replace,\n                    self.formula_attributes[old_coor]['ref']\n                )\n\n        # Do the magic to set up our actual shift    \n        if c.row &gt; row_idx:\n            old_coor = c.coordinate\n            old_cells.add((c.row,c.col_idx))\n            c.row += cnt\n            new_cells[(c.row,c.col_idx)] = c\n            if old_coor in self.formula_attributes:\n                old_fas.add(old_coor)\n                fa = self.formula_attributes[old_coor].copy()\n                new_fas[c.coordinate] = fa\n\n    for coor in old_cells:\n        del self._cells[coor]\n    self._cells.update(new_cells)\n\n    for fa in old_fas:\n        del self.formula_attributes[fa]\n    self.formula_attributes.update(new_fas)\n\n    # Next, we need to shift all the Row Dimensions below our new rows down by cnt...\n    for row in range(len(self.row_dimensions)-1+cnt,row_idx+cnt,-1):\n        new_rd = copy.copy(self.row_dimensions[row-cnt])\n        new_rd.index = row\n        self.row_dimensions[row] = new_rd\n        del self.row_dimensions[row-cnt]\n\n    # Now, create our new rows, with all the pretty cells\n    row_idx += 1\n    for row in range(row_idx,row_idx+cnt):\n        # Create a Row Dimension for our new row\n        new_rd = copy.copy(self.row_dimensions[row-1])\n        new_rd.index = row\n        self.row_dimensions[row] = new_rd\n        for col in range(1,self.max_column):\n            col = get_column_letter(col)\n            cell = self.cell('%s%d'%(col,row))\n            cell.value = None\n            source = self.cell('%s%d'%(col,row-1))\n            if copy_style:\n                cell.number_format = source.number_format\n                cell.font      = source.font.copy()\n                cell.alignment = source.alignment.copy()\n                cell.border    = source.border.copy()\n                cell.fill      = source.fill.copy()\n            if fill_formulae and source.data_type == Cell.TYPE_FORMULA:\n                s_coor = source.coordinate\n                if s_coor in self.formula_attributes and 'ref' not in self.formula_attributes[s_coor]:\n                    fa = self.formula_attributes[s_coor].copy()\n                    self.formula_attributes[cell.coordinate] = fa\n                # print(\"Copying formula from cell %s%d to %s%d\"%(col,row-1,col,row))\n                cell.value = re.sub(\n                    \"(\\$?[A-Z]{1,3}\\$?)%d\"%(row - 1),\n                    lambda m: m.group(1) + str(row),\n                    source.value\n                )\n                cell.data_type = Cell.TYPE_FORMULA\n\n    # Check for Merged Cell Ranges that need to be expanded to contain new cells\n    for cr_idx, cr in enumerate(self.merged_cell_ranges):\n        self.merged_cell_ranges[cr_idx] = CELL_RE.sub(\n            replace,\n            cr\n        )\n\n# Use way:\n# Worksheet.insert_rows = insert_rows\n<\/code><\/pre>\n<h1>3. \u4f7f\u7528xlwings<\/h1>\n<p>\u8fdb\u884c\u4e00\u4e9b\u5217\u5c1d\u8bd5\u548c\u6298\u817e\u4e4b\u540e\uff0c\u7b14\u8005\u653e\u5f03\u4e86\u4f7f\u7528openpyxl\u64cd\u4f5cExcel\u63d2\u5165\u548c\u5220\u9664\u884c\u4e86\uff0c\u5230\u7f51\u4e0a\u5bfb\u89c5\uff0c\u53d1\u73b0\u4e86xlwings\u8fd9\u4e2a\u8f6e\u5b50\uff0c\u8bf4\u660e\u91cc\u5199\u6709api\u80fd\u591f\u8c03\u7528VBA\u7684\u51fd\u6570\uff0c\u8fd9\u5c31\u5f88\u70ab\u9177\u4e86\uff0c\u7136\u540e\u7ffb\u4e86\u7ffb\u6587\u6863\uff0c\u51b3\u5b9a\u4f7f\u7528\u8fd9\u4e2a\u8f6e\u5b50\u64cd\u4f5c\uff0c\u73b0\u8d34\u51fa\u6765\u7b14\u8005\u5199\u7684\u51e0\u6bb5\u4ee3\u7801\u4f5c\u4e3a\u4f7f\u7528\u65b9\u6cd5\u793a\u8303\u3002<\/p>\n<h2>3.1. \u5220\u9664\u884c: range.api.EntireRow.Delete()<\/h2>\n<pre><code class=\"language-python \"># Delete origin row\ntemp_del = 0\nif len(delete_list) &gt; 0:\n    for delete_row in delete_list:\n        # Report schedule\n        print(\"Have alerady done: \" + \\\n                str((temp_del*100)\/\/delete_num) + \"%\")\n        # Delete one row\n        wb_sheet.range('A'+str(delete_row-temp_del)).api.EntireRow.Delete()\n        temp_del = temp_del + 1\nwb.save()\n<\/code><\/pre>\n<p>\u4e0a\u9762\u8fd9\u6bb5\u4ee3\u7801\u4f7f\u7528\u4e86\u4e00\u4e9b\u5c0f\u6280\u5de7\uff0cdelete_list\u50a8\u5b58\u7684\u662f\u539f\u8868\u683c\u4e2d\uff0c\u9700\u8981\u5220\u9664\u7684\u884c\u53f7\uff0c\u5728\u5220\u9664\u8fc7\u7a0b\u4e2d\u7531\u4e8e\u603b\u884c\u6570\u4e5f\u5728\u8ddf\u7740\u51cf\u5c11\uff0c\u6240\u4ee5\u9700\u8981\u628a\u7edd\u5bf9\u884c\u53f7\u8f6c\u6210\u76f8\u5bf9\u884c\u53f7\u8fdb\u884c\u6807\u8bb0\u5220\u9664\uff0c\u8fd9\u4e2a\u8f6c\u6362\u5c31\u662ftemp_del\u53d8\u91cf\u7684\u4f7f\u7528\u76ee\u7684\u3002<\/p>\n<h2>3.2. \u63d2\u5165\u884c: sheet.api.Rows(row_number).Insert()<\/h2>\n<pre><code class=\"language-python \">if key_word == sheet.range('A'+str(i_row+1)).value:\n    # Insert new line\n    sheet.api.Rows(i_row+2).Insert()\n<\/code><\/pre>\n<p>\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u8fd9\u4e2aVBA\u51fd\u6570\u662f\u5411\u4e0a\u63d2\u5165\u7a7a\u884c\uff0c\u5e76\u4e14xlwings\u8fd9\u4e2a\u8f6e\u5b50\u53ea\u80fd\u5728windows\u548cmacos\u7684\u7cfb\u7edf\u4e0b\u4f7f\u7528\uff0c\u6682\u65f6\u4e0d\u652f\u6301Linux\u3002\u4e0d\u8fc7xlwings\u8fd0\u884c\u901f\u5ea6\u8981\u8fdc\u8d85\u8fc7openpyxl\uff0c\u800c\u4e14\u8fd8\u80fd\u76f4\u63a5\u8c03\u7528VBA\u7684\u51fd\u6570\uff0c\u5bf9\u4e8eWPS\u548cExcel\u90fd\u80fd\u517c\u5bb9\uff0c\u7efc\u5408\u6765\u770b\uff0c\u8fd8\u662f\u9009\u62e9xlwings\u6bd4\u8f83\u597d\u4e00\u4e9b\u3002<\/p>\n<hr \/>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"_links":{"self":[{"href":"https:\/\/jiangshibo.cn\/index.php\/wp-json\/wp\/v2\/posts\/47"}],"collection":[{"href":"https:\/\/jiangshibo.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jiangshibo.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jiangshibo.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jiangshibo.cn\/index.php\/wp-json\/wp\/v2\/comments?post=47"}],"version-history":[{"count":2,"href":"https:\/\/jiangshibo.cn\/index.php\/wp-json\/wp\/v2\/posts\/47\/revisions"}],"predecessor-version":[{"id":85,"href":"https:\/\/jiangshibo.cn\/index.php\/wp-json\/wp\/v2\/posts\/47\/revisions\/85"}],"wp:attachment":[{"href":"https:\/\/jiangshibo.cn\/index.php\/wp-json\/wp\/v2\/media?parent=47"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jiangshibo.cn\/index.php\/wp-json\/wp\/v2\/categories?post=47"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jiangshibo.cn\/index.php\/wp-json\/wp\/v2\/tags?post=47"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}