簡體   English   中英

無法使用python將多個.xls文件放入多個.xls文件表中

[英]Can't get multiple .xls file into multiple sheets of a .xls file with python

我正在嘗試找到一種方法,可以將多個.xls文件放到一個單獨的.xls文件中,並用分開的圖紙。 (因此1.xls將進入Sheet1等下)這是我的代碼

    mypath = raw_input("Please enter the directory path for the input files: ")

from os import listdir
from os.path import isfile, join
textfiles = [ join(mypath,f) for f in listdir(mypath) if isfile(join(mypath,f)) and '.txt' in  f]

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False        

import xlwt
import xlrd

style = xlwt.XFStyle()
style.num_format_str = '#,###0.00'  

for textfile in textfiles:
    f = open(textfile, 'r+')
    row_list = []
    for row in f:
        row_list.append(row.split('\t'))
    column_list = zip(*row_list)
    workbook = xlwt.Workbook()
    worksheet = workbook.add_sheet('Sheet1')
    i = 0
    for column in column_list:
        for item in range(len(column)):
            value = column[item].strip()
            if is_number(value):
                worksheet.write(item, i, float(value), style=style)
            else:
                worksheet.write(item, i, value)
        i+=1
    workbook.save(textfile.replace('.txt', '.xls'))

import glob, os
import pandas as pd

writer = pd.ExcelWriter('C:\Users\xxx\Desktop\forpythonscript\minonna.xls')

i=1
for xlsfile in glob.glob(os.path.abspath('C:\Users\xxx\Desktop\forpythonscript\*.xls')):
    df = pd.read_excel(xlsfile)
    df.to_excel(writer, 'sheet%s' % i)
    i +=1

writer.save()       

這是將其運行到anaconda時的錯誤。

Traceback (most recent call last):

在writer.save()中,文件“ C:\\ Users \\ xxx \\ Desktop \\ provaimport.py”,第51行,文件“ C:\\ Users \\ xxx \\ Anaconda2 \\ lib \\ site-packages \\ pandas \\ io \\ excel.py”第1423行,在保存中返回self.book.save(self.path)文件“ C:\\ Users \\ xxx \\ Anaconda2 \\ lib \\ site-packages \\ xlwt \\ Workbook.py”,第710行,在保存doc.save( filename_or_stream,self.get_biff_data())文件“ C:\\ Users \\ xxx \\ Anaconda2 \\ lib \\ site-packages \\ xlwt \\ Workbook.py”,行680,位於get_biff_data self .__ worksheets [self .__ active_sheet] .selected = True IndexError :列表索引超出范圍

我無法發表評論,但我認為這可能導致兩個問題。

  1. 文件夾中保存的工作簿是否只有一張紙? 通常,使用read_excel時,您還要選擇一個標簽名稱以進行讀取。

  2. 你也嘗試過設置以下內容

df.to_excel(writer, 'sheet%s' % i, index=False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM