簡介
開發了一個將指定格式的文本轉換成xls表格的程序,需要安裝xlwt。
說明
支持多個sheet。
使用方法
python txt2xls.py student.txt student.xls
txt樣例
tablename 計科0801班
start
title 姓名 年齡 性別
notitle 張三 22 男
notitle 韓梅梅 21 女
end
br
tablename 計科0802班
start
title 姓名 年齡 性別
notitle 李四 22 男
notitle Lily 21 女
end
br
tablename 計科0803班
start
title 姓名 年齡 性別
notitle Jim 22 男
notitle Lucy 21 女
end
txt格式說明
每行以\t分割。
第一列表示標誌符,標誌該行的意義。
各個標誌符具體含義如下:
br 表示提示程序換行
tablename 表示表格名稱,可用於生成sheet
start 表示表格開始
title 表示表格的標題欄
notitle 表示表格的非標題欄
end 表示表格結束
轉換效果
轉換代碼
#!/usr/bin/env python
#coding:utf8
import sys
import xlwt
if len(sys.argv) != 3:
print "usage:"
print "\tpython %s ORI_FILEPATH RESULT_FILEPATH" % sys.argv[0]
exit(-1)
ori_file = sys.argv[1]
result_file = sys.argv[2]
wbk = xlwt.Workbook(encoding = "utf8")
sheet_list = []
sheet_index = -1
cur_row = 0
for line in open(ori_file):
splits = line.strip().split("\t")
if len(splits) == 0:
continue
mark = splits[0]
if mark == "start":
continue
elif mark == "end":
continue
elif mark == "br":
cur_row += 1
elif mark == "tablename":
sheet_list.append( wbk.add_sheet(splits[1]) )
sheet_index += 1
cur_row = 0
elif mark == "title" or mark == "notitle":
for col in range(len(splits[1:])):
sheet_list[sheet_index].write(cur_row, col, splits[1:][col])
cur_row += 1
else:
continue
wbk.save(result_file)