如何parsingExcel表格中的数据框(使用Python,可能是Pandas)

我正在处理严重的Excel表格,我试图parsing并写入数据库。

每张纸可以有多个表。 尽pipe这些可能的表格的标题是已知的,但是在任何给定的表格上哪些表格不是,它们在表格上的确切位置(表格不以一致的方式alignment)。 我已经添加了两个可能的工作表布局的图片来说明这一点: 这个布局有两个表,而这个表有第一个表的所有表,但不在同一个位置,加上一个额外的表。

我所知道的是:

  1. 所有可能的表头,所以每个单独的表可以通过它的头标识
  2. 表格由空格分隔。 他们不相互接触。

我的问题是否有一个干净的方式来处理这个使用一些Python模块,如pandas?

我目前的做法

我目前正在转换为.csv并parsing每一行。 我将每行分割为空白单元格,并处理该行的第一部分(应该属于最左边的表格)。 行的其余部分排队并稍后以相同的方式处理。 然后我读这个first_part并检查它是否是一个标题行。 如果是这样,我用它来确定我正在处理哪个表(这是存储在一个全球current_df )。 后面的行不是标题行被送入这个表(这里我使用pandas.DataFrame为我的表)。

目前的代码是低于(大部分是不完整的,未经testing,但它应该传达上面的方法):

 class DFManager(object): # keeps track of current table and its headers current_df = None current_headers = [] def set_current_df(self, df, headers): self.current_headers = headers self.current_df = df def split_row(row, separator): while row and row[0] == separator: row.pop(0) while row and row[-1] == separator: row.pop() if separator in row: split_index = row.index(separator) return row[:split_index], row[split_index:] else: return row, [] def process_df_row(row, dfmgr): df = df_with_header(row) # returns the dataframe with these headers if df is None: # is not a header row, add it to current df df = dfmgr.current_df add_row_to_df(row, df) else: dfmgr.set_current_df(df, row) # this is passed the Excel sheet def populate_dataframes(xl_sheet): dfmgr = DFManager() row_queue = Queue() for row in xl_sheet: row_queue.put(row) for row in iter(row_queue.get, None): if not row: continue first_part, remainder = split_row(row) row_queue.put(remainder) process_df_row(first_part, dfmgr) 

这是一个特殊的情况,现成的模块可能没有“干净”的方式来做到这一点。

一种方法可以使用你已经有的头信息find每个表的起始索引,像这个解决scheme( Python Pandas – 读取包含多个表的csv文件 ),但是在列方向也有一个偏移量。

一旦你有了每个表的起始位置,你就需要确定宽度(先验知道或者直到下一个空白列读取发现),并将这些列读入数据框直到表的结尾。

基于索引的方法而不是基于队列的方法的好处是,您不需要重新发现每行中的分隔符所在的位置,或者跟踪哪些行分段属于哪个表。 对每行> 2个表也是不可知的。