如何将excel的每一行内容都转化成一个txt文件(vba方法&python方法)

快捷键 Alt + F11 打开宏

Private Sub CommandButton1_Click()

mypath = "E:\test\"
num = 160 ' 行数
lies = 1 ' 列数
jiange = " " ' 列间隔符,自己定
For i = 1 To num
For j = 1 To lies
temp = Trim(Worksheets(1).Cells(i, j).Value) + jiange + temp
Next j
outfile = mypath + CStr(i) + ".txt"
Open outfile For Output As #1 ' 打开输出文件。
Print #1, temp
Close #1 ' 关闭文件。
Next i

End Sub

缺点:

1.用vba的方法得到的txt文件是ANSI格式的,后面要使用这些txt文件的话,可能要转化utf-8形式的,所以有点麻烦;

2.这种方式得到的txt文件很大,文件一多,后面处理严重收到影响。

所以用了python来处理

import os
import xlrd
os.chdir(r"C:\Users\Desktop\shiji\news_data\2013")

def read():
    file_path = 'no_data2.xlsx'

    data = xlrd.open_workbook(file_path)

    table = data.sheet_by_name('Sheet1')

    nrows = table.nrows


    for i in range(0, nrows):
        file = open('./no_data2/no_data20803_' + str(i) + '.txt', 'wb+')
        file.write(str(table.cell(i, 0).value).encode(encoding='utf-8'))     
        file.close()
    return 'done.'

read()

 用python 处理的优点:出来txt文件很小,很多txt文件都不成问题,且出来的txt文件是utf-8.

猜你喜欢

转载自www.cnblogs.com/lxh1208891835/p/9492177.html