如何使用文本文件制作excel文件?

时间:2017-07-24 05:21:16

标签: python openpyxl

我使用python为疯狂的excel制作了一些脚本。 我刚刚学习初学者关于python。 所以我的脚本太长了。 谁可以做空?

我想要制作单元格边框

我想读一些文本文件。 直到细胞。

下面是文本文件。

Node1_aggr0,492GB,469GB,22GB,95%
Node1_aggr0/.snapshot,0GB,0GB,0GB,0%
Node1_aggr1,73333GB,65602GB,7731GB,89%
Node1_aggr1/.snapshot,0GB,0GB,0GB,0%
Node1_aggr2,19194GB,16147GB,3047GB,84%
Node1_aggr2/.snapshot,0GB,0GB,0GB,0%
Node2_aggr0,492GB,469GB,22GB,95%
Node2_aggr0/.snapshot,0GB,0GB,0GB,0%
Node2_aggr1,73333GB,66823GB,6510GB,91%
Node2_aggr1/.snapshot,0GB,0GB,0GB,0%
Node2_aggr2,19194GB,16834GB,2359GB,88%
Node2_aggr2/.snapshot,0GB,0GB,0GB,0%

我在下面写了一些脚本。如何缩短?

from openpyxl import Workbook
from openpyxl.styles import Font, Side, Border

wb = Workbook()
ws1 = wb.active
ws1.title = "Example1"

ws1['A1'] = "aggr info"
ws1['A2'] = "aggr"
ws1['B2'] = "total(GB)"
ws1['C2'] = "used(GB)"
ws1['D2'] = "avail(GB)"

with open("excel.txt", "r") as f:
        n = 2
        for line in f:
                line = line.split(',')
                n = int(n)
                n += 1
                n = str(n)
'''
                c1 = "A" + n
                c2 = "B" + n
                c3 = "C" + n
                c4 = "D" + n
'''
                c1, c2, c3, c4 = ["A" + n, "B" + n, "C" + n, "D" + n]
                c1 = ws1.cell(c1)
                c2 = ws1.cell(c2)
                c3 = ws1.cell(c3)
                c4 = ws1.cell(c4)
                c1.value = line[0]
                c2.value = line[1]
                c3.value = line[2]
                c4.value = line[3]
#               c1.font = Font(name='Arial', size=14)
                c1.border = Border(left=Side(border_style="thin", color='FF000000'),right=Side(border_style="thin", color='FF000000'),top=Side(border_style="thin", color='FF000000'),bottom=Side(border_style="thin", color='FF000000'))
                c2.border = Border(left=Side(border_style="thin", color='FF000000'),right=Side(border_style="thin", color='FF000000'),top=Side(border_style="thin", color='FF000000'),bottom=Side(border_style="thin", color='FF000000'))
                c3.border = Border(left=Side(border_style="thin", color='FF000000'),right=Side(border_style="thin", color='FF000000'),top=Side(border_style="thin", color='FF000000'),bottom=Side(border_style="thin", color='FF000000'))
                c4.border = Border(left=Side(border_style="thin", color='FF000000'),right=Side(border_style="thin", color='FF000000'),top=Side(border_style="thin", color='FF000000'),bottom=Side(border_style="thin", color='FF000000'))

wb.save('test.xlsx')

我想要这个结果。 enter image description here

1 个答案:

答案 0 :(得分:1)

如果使用pandas.read_table方法,这将非常容易。

import pandas as pd
file = 'text_file.txt' # your text file 
table = pd.read_table(file, encoding='utf_16', sep=',', header=None)

table.to_csv('newfile.csv') # to get a csv file
table.to_excel('newfile.xlsx') # to get excel file

如果您未安装pandas,可以按照here的说明进行安装。

相关问题