简体   繁体   English

如何使用Python从Excel中读取和提取数据并将其粘贴到文本文件中的现有文本中?

[英]How to read and extract data from Excel and paste it into an existing text in a text file using Python?

I want to automatically create several text files and in them include some information I have stored in one excel file. 我想自动创建几个文本文件,并且其中包含一些存储在一个excel文件中的信息。 The excel file has a lot of information stored, one row with several cells for each subject and information from each subject is to be written in different text files. excel文件中存储了很多信息,每一主题的一行包含多个单元格,并且每个主题的信息都将写入不同的文本文件中。 The data from the excel file is supposed to be pasted in between a text written in the text files (see code below). excel文件中的数据应该粘贴在文本文件中写入的文本之间(请参见下面的代码)。

I have already made a code that writes the other information I need in each text file, but I do not know how to get the data from excel to the text file: 我已经编写了一个代码,可以在每个文本文件中写入所需的其他信息,但是我不知道如何将数据从excel获取到文本文件:

import xlrd

file = open("testfile.txt", "w")

file.write("text1.\n")

file.write("text2\n")

file.write("text3\n")

file.write("text4\n")

wb = xlrd.open_workbook(r"C:Data.xls")

I do not know how to continue the code to get it to loop through the excel file, row by row, extract some of the data, paste it into the text in the text file, close the text file and open a new one and do the same. 我不知道如何继续执行代码以使其逐行遍历excel文件,提取一些数据,将其粘贴到文本文件中的文本中,关闭文本文件并打开一个新文件并执行相同。

So the text files should end up looking like this: 因此,文本文件最终应如下所示:

text1 copied data from excel1

text2 copied data from excel2

text3 copied data from excel3

etc... 等等...

Can someone help me? 有人能帮我吗? I am sorry if this is basic, I am new to python. 很抱歉,如果这是基本知识,我是python的新手。 Working in Python 3.4.1 使用Python 3.4.1

I would do that: 我会这样做:

import xlrd
xlsfilename='test.xlsx'
test = xlrd.open_workbook(xlsfilename)
number_subjetcs=50 # assuming it is known, otherwise you need a 'foreach line' loop
number_columns=3 # assuming it is known...
for row in range(number_subjetcs): 
    txtfilename = 'testfile' + str(row) + '.txt'
    with open(txtfilename, "w") as f:
        for col in range(number_columns):
            s1 = 'text' + str(col+1) + ' : '
            f.write(s1)
            # assuming there is only 1 sheet in the excel file
            val = test.sheets()[0].cell(row,col).value
            s2 = str(val) + '\n'
            f.write(s2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM