Python结合Excel电子表格

时间:2015-05-06 09:08:29

标签: python excel

大家好......使用Panda组合Excel电子表格的问题。

问题在于,组合时列的序列会丢失。如果要合并的文件越多,格式就越差。

如果给出错误消息,如果文件数量很大。

ValueError: column index (256) not an int in range(256) 

我正在使用的是:

import pandas as pd

df = pd.DataFrame()

for f in ['c:\\1635.xls', 'c:\\1644.xls']:
    data = pd.read_excel(f, 'Sheet1')
    data.index = [os.path.basename(f)] * len(data)
    df = df.append(data)

df.to_excel('c:\\CB.xls')

原始文件和组合看起来像: enter image description here

什么是组合大量此类类似Excel文件的最佳方式?

感谢。

2 个答案:

答案 0 :(得分:1)

我通常使用xlrdxlwt

#!/usr/bin/env python
# encoding: utf-8

import xlwt
import xlrd
import os


current_file = xlwt.Workbook()
write_table = current_file.add_sheet('sheet1', cell_overwrite_ok=True)

key_list = [u'City', u'Country', u'Received Date', u'Shipping Date', u'Weight', u'1635']
for title_index, text in enumerate(key_list):
    write_table.write(0, title_index, text)


file_list = ['1635.xlsx', '1644.xlsx']

i = 1
for name in file_list:
    data = xlrd.open_workbook(name)

    table = data.sheets()[0]
    nrows = table.nrows
    for row in range(nrows):
        if row == 0:
            continue
        for index, context in enumerate(table.row_values(row)):
            write_table.write(i, index, context)
        i += 1


current_file.save(os.getcwd() + '/result.xls')

答案 1 :(得分:1)

而不是data.index = [os.path.basename(f)] * len(data),您应该使用df.reset_index()

例如:

1.xlsx:

a   b
1   1
2   2
3   3

2.xlsx:

a   b
4   4
5   5
6   6

代码:

 df = pd.DataFrame()

 for f in [r"C:\Users\Adi\Desktop\1.xlsx", r"C:\Users\Adi\Desktop\2.xlsx"]:
    data = pd.read_excel(f, 'Sheet1')
    df = df.append(data)

 df.reset_index(inplace=True, drop=True)
 df.to_excel('c:\\CB.xls')

cb.xls:

        a   b
    0   1   1
    1   2   2
    2   3   3
    3   4   4
    4   5   5
    5   6   6

如果您不希望数据集的索引位于输出文件中,则可以使用df.to_excel('c:\\CB.xls', index=False)

相关问题