2017-07-11 80 views
0

已经有一个文件夹完整的Excel文件。一个恼人的方面是它们都是.xls(而不是.xlsx)。Python合并.xls文件

我需要做的是在每个.xls文件中读取,删除前7行,然后取出剩余的文档并将其添加到“master.xlsx”文件中。 (注意:master.xlsx不一定是预先存在的,可以新创建)

我还没有开始尝试删除行,只是试图简单地合并它们,但无法弄清楚如何。我是否需要以某种方式将所有.xls转换为.xlsx,然后尝试合并?我花了几个小时看着其他堆栈溢出问题和在线资源。这似乎是某种古老的技术。另外,值得一提的是我正在使用Python3。

这里是我到目前为止的代码:

import os 
from numpy import genfromtxt 
import re 
import urllib.request 
import pandas as pd 


# script directory 
script_dir = os.path.dirname(r'C:/Users/Kenny/Desktop/pythonReports/') 


# get array list of files 
files = [] 
file_abs_path = script_dir + '/excels/' 
for file in os.listdir(file_abs_path): 
    if file.endswith('.xls'): 
     excel_file_path = script_dir + '/excels/' + file 
     files.append(excel_file_path) 

# f is full file path 
df_array = [] 
writer = pd.ExcelWriter('master.xlsx') 
for f in files: 
    sheet = pd.read_html(f) 

    for n, df in enumerate(sheet): 
     df_array.append(df) 
     # df = df.append(df) 
    # df.to_excel(writer,'sheet%s' % n) 
print(df_array) 

for df in df_array: 
     # new_df = new_df.append(df) 
     new_df = pd.concat(df_array) 
     new_df.to_excel(writer,'sheet%s' % n) 
     writer.save() 
    # print(sheet) 

在某些时候,我没有得到的错误,这是阅读和正确复制的内容,但它会重新写入master.xlsx并覆盖旧的东西,而不是连接它。现在

编辑

合并工作。我现在的困难是我需要从单元中获取数据,删除前7行,然后创建一个新列并将该数据添加到该列中的所有行(针对文档的长度)。

我认为有一件事情使得这个难题是我必须使用read_html(),因为read_excel()不起作用。我得到以下错误:

Traceback (most recent call last): 
    File "script.py", line 83, in <module> 
    sheet = pd.read_excel(f) 
    File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\io\excel.py", line 200, in read_excel 
    io = ExcelFile(io, engine=engine) 
    File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\io\excel.py", line 257, in __init__ 
    self.book = xlrd.open_workbook(io) 
    File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\__init__.py", line 441, in open_workbook 
    ragged_rows=ragged_rows, 
    File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 91, in open_workbook_xls 
    biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) 
    File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 1230, in getbof 
    bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8]) 
    File "C:\Users\Kenny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 1224, in bof_error 
    raise XLRDError('Unsupported format, or corrupt file: ' + msg) 
xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\n<html>\n' 
+1

'new_df = pd.concat(df_array)' iirc ...你只是简单地将'new_df'分配给'df' ... –

+0

同意Corley,'pd.concat(df)'并没有合并任何东西,而是只给你你握手的框架它。但是'pd.read_excel'也不处理xls文件? –

+0

谢谢,这是有道理的,并有很大的帮助!我想我正走在正确的轨道上。现在我可以在文件的结尾添加新的数据。现在我想我需要在添加到数组之前发现删除前7行。将更新最新代码的问题。 – Kenny

回答

0

这里是我的合并(有一个可爱的小动态变化的print语句太)最终解决方案:

# Merge all .xlsx files into one 'master.xlsx' 

files = get_files('/xlsx/', '.xlsx') 
df_array = [] 
all_data = pd.DataFrame() 
writer = pd.ExcelWriter('master.xlsx') 

for i, f in enumerate(files, start=1): 
    sheet = pd.read_excel(f) 
    all_data = all_data.append(sheet, ignore_index=True) 

    # progress of entire list 
    if i <= len(files): 
     print('\r{:*^7}{:.0f}%'.format('Merging: ', i/len(files)*100), end='') 

all_data.to_excel(writer, 'sheet') 
writer.save() 
你可能想