首页 > 解决方案 > 从许多文本文件制作 Excel 电子表格

问题描述

我有几个输入文本文件,如下所示: [ 文本文件作为图像(太大而无法显示内联).

我想做的是制作一个这样的 Excel 电子表格:

在此处输入图像描述

我正在使用的代码是从堆栈溢出站点的其他地方获得的:

import pandas as pd
import numpy as np
import glob
import xlsxwriter

# Creating a dataframe and saving as test_1.txt/test_2.txt in current directory
# feel free to remove the next 3 lines if yo want to test in your directory
#df = pd.DataFrame(np.random.randn(100, 5), columns=list('DetectorID','Measurementdate','FileName','itemID','Pu240'))
df = pd.DataFrame(np.random.randn(3, 12), columns= ['Facility','Materialbalance area','Detector type','Detector id','Electronic id','Measurement date','Results file name','Item id','Singles','Doubles','Triples','Quads'])
df.to_csv('test_1.txt', index=True)
#f.to_csv('test_2.txt', index=False)

txt_list = [] # empty list
sheet_list = [] # empty list

# a for loop through filenames matching a specified pattern (.txt) in the current directory
for infile in glob.glob(r"C:\\Users\137678\spyder-py3:\txt\*.VER"): 

    outfile = infile.replace("C:\\Users\137678\spyder-py3:\txt\Results.xlsx", '') #removing '.txt' for excel sheet names
    sheet_list.append(outfile) #appending for excel sheet name to sheet_list
    txt_list.append(infile) #appending for '...txt' to txtt_list

writer = pd.ExcelWriter('summary.xlsx', engine='xlsxwriter')

# a for loop through all elements in txt_list

for i in range(0, len(txt_list)):
#    df = pd.read_csv('%s' % (ver_list[i])) #reading element from txt_list at index = i 
    df = pd.read_csv('%s' % (txt_list[i])) #reading element from txt_list at index = i    
    df.to_excel(writer, sheet_name='%s' % (sheet_list[i]), index=False) #reading element from sheet_list at index = i 

writer.save()

该代码将 test1.txt 和 test2.txt 创建为带有奇怪数字的 csv。它还创建了一个空的摘要 Excel 电子表格。谁能指出我正确的方向?

标签: pythonexcelcsv

解决方案


推荐阅读