简体   繁体   English

使用 xlsxwriter 将文本文件数据迁移到 excel 未完全更新

[英]Migrating text file data to excel using xlsxwriter is not updating completely

test.txt: A 25 12345 B 90 67890 C 31 24680 D 89 45678 test.txt:A 25 12345 B 90 67890 C 31 24680 D 89 45678

expected output: A1 A A2 25 A3 12345 A4 B A5 90 A6 67890 ......预期输出:A1 A A2 25 A3 12345 A4 B A5 90 A6 67890 ......

only last three data is coming in the excel excel中只有最后三个数据

import xlsxwriter

workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()

with open('test.txt', 'r') as f:
    for i in f.readlines():
        for j,k in enumerate(i.split()):
            worksheet.write('A'+str(j+1), k)
    workbook.close()

Inside the inner loop, j will always be the enumeration 0,1,2 and so you are repeatedly writing to cells A1 , A2 , and A3 .在内部循环中, j将始终是枚举0,1,2 ,因此您重复写入单元格A1A2A3 You can see this for yourself if you print the result to your console:如果将结果打印到控制台,您可以亲眼看到:

A1 A
A2 25
A3 12345
A1 B
A2 90
A3 67890
A1 C
A2 31
A3 24680
A1 D
A2 89
A3 45678

You always want to increase the number in the first argument of write so the next row gets indexed;您总是希望增加write的第一个参数中的数字,以便对下一行进行索引; the value to increase with is the length of the splitted list ( 3 for your current input but to make sure I use the actual length of each line below).要增加的值是拆分列表的长度(当前输入为3 ,但要确保我使用下面每行的实际长度)。 Because Excel starts counting rows at 1 , this counter needs to start with 1 as well.因为 Excel 从1开始计算行数,所以这个计数器也需要从1开始。 This will work:这将起作用:

counter = 1
for i in f.readlines():
    for j,k in enumerate(i.split()):
         worksheet.write('A'+str(j+counter), k)
    counter += len(i.split())

Like your own code and the expected output, all it will do is fill the first column only, with each value in the input, ignoring the line breaks.就像你自己的代码和预期的输出一样,它所做的只是填充第一列,输入中的每个值,忽略换行符。

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

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