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

How can make excel file using text file?

我使用 python 为 mad 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')

我想要这个结果。

如果用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