python3.5 - 从txt文件写入excel2007,后台打印顺序正常,但是打开excel实际数据没有按照顺序排列

查看:105
本文介绍了python3.5 - 从txt文件写入excel2007,后台打印顺序正常,但是打开excel实际数据没有按照顺序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

openpyxl的版本是:openpyxl-2.5.0a1
我的目的是将txt中的文本写入excel中,其实是一个自己想实现的一个小功能
但是从txt文件写入excel2007,后台打印顺序正常,但是打开excel实际数据没有按照顺序排列。
一直想不通,所以向大家提问。

图1 是txt打开的, 图2是生成后excel文件,图三是后台运行打印的数据。
图三在【E1】打印了Remark,这个不知道如何出现的,余下的,是按照正常的顺序打印。但是到了excel中出现了顺序不一致的情况。望大牛解答。感谢!

import openpyxl

loadActive = open('F:\\pythoncode\\ActivityList.txt', encoding="utf-16")
wb = openpyxl.load_workbook('F:\\pythoncode\\example_1.xlsx')
# ' '.join(ActiveList)

dataActive = loadActive.readlines()

sheet = wb.get_active_sheet()
c = []
for i in range(len(dataActive)):
    c += dataActive[i].split('\t')

j = 1
columnNum = 1
for i in range(int(len(c))):
    if i < 3:
        sheet.cell(row = j,column = columnNum).value = c[i]
        columnNum += 1
    else:
        if i % 4 == 0:
            j += 1
            columnNum = 1
            sheet.cell(row = j,column = columnNum).value = c[i]
            print(sheet.cell(row = j,column = columnNum))
            print(c[i])
        else:
            sheet.cell(row = j,column = columnNum).value = c[i]
            columnNum += 1
            print(sheet.cell(row = j,column = columnNum))
            print(c[i])

loadActive.close()
wb.save('F:\\pythoncode\\example_1.xlsx')


Id    ActivityId    TimeDesc    Remark
int_cs    int_c    string_c    string
note    Actid    timessss    memo
1    2    9:00-9:40    hello1
2    13    10:00-10:40    hello2
3    43    11:30-11:45    hello3
4    22    12:00-14:00    hello4
5    43    12:30-12:45    hello5
6    2    15:00-15:40    hello6
7    13    16:00-16:40    hello7
8    43    17:30-17:45    hello8
9    22    18:00-20:00    hello9
10    43    18:30-18:45    hello10
11    25    20:15    hello11
12    23    20:30-20:45    hello12
13    1    20:45-21:15    hello13

解决方案

import openpyxl

loadActive = open('F:\\pythoncode\\ActivityList.txt', encoding="utf-16")
wb = openpyxl.load_workbook('F:\\pythoncode\\example_1.xlsx')
# ' '.join(ActiveList)

dataActive = loadActive.readlines()

print(dataActive)

sheet = wb.get_active_sheet()
c = []
#this loop to solve the \t and \n      

 for i in range(len(dataActive)):
    c1 = dataActive[i].rstrip('\n')
    c += c1.split('\t')
    print(c[i])
print(c)

j = 1
columnNum = 1
for i in range(int(len(c))):
#delete simplified the logic
    if i % 4 == 0:
        j += 1
        columnNum = 1

    sheet.cell(row = j,column = columnNum).value = c[i]
    columnNum += 1

loadActive.close()
wb.save('F:\\pythoncode\\example_1.xlsx')

这样处理打印完整了,但是会引出空行。

这篇关于python3.5 - 从txt文件写入excel2007,后台打印顺序正常,但是打开excel实际数据没有按照顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆