提交 4c1d6bd6 编写于 作者: S ShaShiDiZhuanLan

Python3读写Excel文件

上级 e0f5c463
# encoding: utf-8
"""
Author: 沙振宇
CreateTime: 2019-12-6
UpdateTime: 2019-12-6
Info: 可读写Excel2007 XLSX/XLSM文件, 不可以处理XLS文件
"""
import openpyxl
def write_excel():
f = openpyxl.Workbook() # 创建工作簿
# sheet1 = f.create_sheet()
print("sheet names:", f.sheetnames)
sheet1 = f.active # 当前工作表的名称
print("sheet1:", sheet1)
row_file = 5 # 生成5行
col_three = 3 # 生成3列
for row in range(row_file):
for col in range(col_three):
rw = row + 1
cl = col + 1
if col % 2 == 0:
sheet1.cell(row=rw, column=cl, value='1')
else:
sheet1.cell(row=rw, column=cl, value='2')
f.save("file/生成的Excel_OPENPYXL.xlsx") # 保存文件
if __name__ == '__main__':
# 写入Excel
write_excel()
print('openpyxl 写入成功')
\ No newline at end of file
# encoding: utf-8
"""
Author: 沙振宇
CreateTime: 2019-12-6
UpdateTime: 2019-12-6
Info: 读取Excel文件,可以读取xls,也可以读xlsx
"""
import xlrd
def read_excel():
excel_tables = []
file_name = 'file/模板.xls'
workbook = xlrd.open_workbook(file_name) # 打开文件
sheet = workbook.sheet_by_index(0) # 根据sheet索引或者名称获取sheet内容 sheet索引从0开始
print(file_name, sheet.name, sheet.nrows, sheet.ncols) # sheet的名称,行数,列数
print("获取第2行内容:", sheet.row_values(1))
print("获取第3列内容:", sheet.col_values(2))
for rown in range(sheet.nrows):
array = {'L1': '', 'L2': '', 'Question': '', 'Answer': '', 'Similar':''}
array['L1'] = sheet.cell_value(rown, 0)
array['L2'] = sheet.cell_value(rown, 1)
array['Question'] = sheet.cell_value(rown, 2)
array['Answer'] = sheet.cell_value(rown, 4)
array['Similar'] = sheet.cell_value(rown, 6)
excel_tables.append(array)
print("一共%d条数据"%len(excel_tables))
return excel_tables
if __name__ == '__main__':
# 读取Excel
read_excel()
\ No newline at end of file
# encoding: utf-8
"""
Author: 沙振宇
CreateTime: 2019-12-6
UpdateTime: 2019-12-6
Info: 只能写,不能读。生成的文件后缀名为.xlsx,不能生成xls文件,最大能够支持1048576行数据,16384列数据
"""
import xlsxwriter
# 写excel
def write_excel():
workbook = xlsxwriter.Workbook('file/生成的Excel_XLSXWRITER.xlsx') # 创建一个excel文件
worksheet = workbook.add_worksheet(u'sheet1') # 在文件中创建一个名为TEST的sheet,不加名字默认为sheet1
worksheet.set_column('A:A', 20) # 设置第一列宽度为20像素
bold = workbook.add_format({'bold': True}) # 设置一个加粗的格式对象
worksheet.write('A1', 'HELLO') # 在A1单元格写上HELLO
worksheet.write('A2', 'WORLD', bold) # 在A2上写上WORLD,并且设置为加粗
worksheet.write('B2', U'中文测试', bold) # 在B2上写上中文加粗
worksheet.write(2, 0, 32) # 使用行列的方式写上数字32,35,5
worksheet.write(3, 0, 35.5) # 使用行列的时候第一行起始为0,所以2,0代表着第三行的第一列,等价于A4
worksheet.write(4, 0, '=SUM(A3:A4)') # 写上excel公式
workbook.close()
print("写入\"file/生成的Excel_XLSXWRITER.xlsx\"")
if __name__ == '__main__':
# 写入Excel
write_excel()
\ No newline at end of file
# encoding: utf-8
"""
Author: 沙振宇
CreateTime: 2019-12-6
UpdateTime: 2019-12-6
Info: 写Excel文件 xlwt 中生成的xls文件最多能支持 65536 行数据。
"""
import xlwt
def write_excel():
myWorkbook = xlwt.Workbook() # 创建Excel工作薄
mySheet = myWorkbook.add_sheet('A Test Sheet') # 添加Excel工作表
myStyle = xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00') # 写入数据 数据格式
mySheet.write(1, 2, 1234.56, myStyle)
mySheet.write(2, 0, 1) #写入A3,数值等于1
mySheet.write(2, 1, 1) #写入B3,数值等于1
mySheet.write(2, 2, xlwt.Formula("A3+B3")) #写入C3,数值等于2(A3+B3)
new_path = 'file/生成的Excel_XLWT.xls'
myWorkbook.save(new_path) # 保存
print(new_path)
if __name__ == '__main__':
# 写入Excel
write_excel()
\ No newline at end of file
# Demo_Excel_Python
# 1、Python语言的应用 之 Demo_Excel_Python
Python3读写Excel文件,包含:xlrd、xlwt、openpyxl、xlsxwriter等方式
<BR/>
# 2、更新信息
开发者:沙振宇(沙师弟专栏) <BR/>
创建时间:2019-12-6<BR/>
最后一次更新时间:2019-12-6<BR/>
<BR/>
CSDN博客地址——Python开发 之 Python3读写Excel文件(较全):<BR/>
https://shazhenyu.blog.csdn.net/article/details/83104653 <BR/>
<BR/>
# 3、xlrd、xlwt、openpyxl、xlsxwrite
<BR/>
# 4、结果
![image]()
\ No newline at end of file
此差异已折叠。
文件已添加
文件已添加
# encoding: utf-8
"""
Author: 沙振宇
CreateTime: 2019-10-30
UpdateTime: 2019-12-6
Info: 读取Txt文件,并写Excel文件
"""
import xlrd
import xlsxwriter
# 读取(模板.xls)Excel文件
def read_old_excel():
excel_tables = []
file_name = 'file/模板.xls'
workbook = xlrd.open_workbook(file_name) # 打开文件
sheet = workbook.sheet_by_index(0) # 根据sheet索引或者名称获取sheet内容 sheet索引从0开始
print(file_name, sheet.name, sheet.nrows, sheet.ncols) # sheet的名称,行数,列数
print("获取第2行内容:", sheet.row_values(1))
print("获取第3列内容:", sheet.col_values(2))
for rown in range(sheet.nrows):
array = {'L1': '', 'L2': '', 'Question': '', 'Answer': '', 'Similar':''}
array['L1'] = sheet.cell_value(rown, 0)
array['L2'] = sheet.cell_value(rown, 1)
array['Question'] = sheet.cell_value(rown, 2)
array['Answer'] = sheet.cell_value(rown, 4)
array['Similar'] = sheet.cell_value(rown, 6)
excel_tables.append(array)
print("read_old_excel 一共%d条数据"%len(excel_tables))
return excel_tables
# 写(生成的Excel.xlsx)Excel文件
def write_old_excel():
workbook = xlsxwriter.Workbook('file/生成的Excel_main.xlsx') # 创建一个excel文件
worksheet = workbook.add_worksheet() # 在文件中创建一个名为TEST的sheet,不加名字默认为sheet1
worksheet.write('A1', '1级分类')
worksheet.write('B1', '2级分类')
worksheet.write('C1', 'FAQ问题')
worksheet.write('D1', '渠道')
worksheet.write('E1', 'FAQ回答')
worksheet.write('F1', '关联FAQ问题')
worksheet.write('G1', 'FAQ相似问句')
excel_tables = read_old_excel()
print("write_old_excel 一共%d条数据"%len(excel_tables))
cowNum = 1
for list in excel_tables:
L1List = list['L1']
L2List = list['L2']
QuestionList = list['Question']
AnswerList = list['Answer']
Similar = list['Similar']
SimilarList = Similar.split('||')
if L1List == "1级分类":
continue
# print("SimilarList",SimilarList)
worksheet.write(cowNum, 0, L1List)
worksheet.write(cowNum, 1, L2List)
worksheet.write(cowNum, 2, QuestionList)
worksheet.write(cowNum, 4, AnswerList)
for item in SimilarList:
worksheet.write(cowNum, 6, item)
cowNum += 1
workbook.close()
# 读取数据源文件
def read_txt():
with open('file/data.txt', "r",encoding="utf-8") as f: # 设置文件对象
txtList = f.readlines() # 可以是随便对文件的操作
return txtList
# 写(对比.xlsx)Excel文件
def write_excel(txtList):
workbook = xlsxwriter.Workbook('file/对比.xlsx') # 创建一个excel文件
worksheet = workbook.add_worksheet() # 在文件中创建一个名为TEST的sheet,不加名字默认为sheet1
worksheet.write('A1', '工单头')
worksheet.write('B1', 'words')
worksheet.write('C1', 'cor')
worksheet.write('D1', 'ins')
worksheet.write('E1', 'del')
worksheet.write('F1', 'sub')
worksheet.write('G1', 'corr')
worksheet.write('H1', 'cer')
worksheet.write('I1', 'ref')
worksheet.write('J1', 'res')
print("write_excel 一共%d条"%len(txtList))
value_297 = []
for index,value in enumerate (txtList):
if index < 297 :
curIndex = int(index/3)+1
if index % 3 == 1:
str1 = str(value).split("ref: ")[1]
worksheet.write(curIndex, 8, str1)
elif index %3 == 2:
str2 = str(value).split("res: ")[1]
worksheet.write(curIndex, 9, str2)
else:
str_t = str(value)[0:19]
worksheet.write(curIndex, 0, str_t)
str_w = str(value).split(str_t)[1].split(") ")
str_w1 = str_w[0][8:]
str_w2 = str_w1.split(",")
# 中间
str_words = str_w2[0]
worksheet.write(curIndex, 1, str_words)
str_cor = str_w2[1].split("=")[1]
worksheet.write(curIndex, 2, str_cor)
str_ins = str_w2[2].split("=")[1]
worksheet.write(curIndex, 3, str_ins)
str_del = str_w2[3].split("=")[1]
worksheet.write(curIndex, 4, str_del)
str_sub = str_w2[4].split("=")[1]
worksheet.write(curIndex, 5, str_sub)
str_l = str_w[1].split(",")
str_corr=str_l[0].split("=")[1]
worksheet.write(curIndex, 6, str_corr)
str_cer=str_l[1].split("=")[1]
worksheet.write(curIndex, 7, str_cer)
else:
value_297.append(index)
print(">= 297: ", value_297)
workbook.close()
if __name__ == '__main__':
write_old_excel()
txtList = read_txt()
write_excel(txtList)
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册