这里,我用到的是xlwt和xlrd这两个库分别进行写入和读取
首先,安装库
pip install xlwt
pip install xlrd
------------------------------具体如下
import xlwt
#file以utf-8格式打开
file = xlwt.Workbook(encoding='utf-8')
#创建一个名为data的表单
table = file.add_sheet('data',cell_overwrite_ok=True)
#表头信息
table_head = ['name', 'case_number', 'message','related_crs','case_owner','case_comments']
#将表头信息写入到表格的第一行
for i in range(len(table_head)):
table.write(0, i, table_head[i])
# produce_info_list2 是一个二维列表[['x':'1223','xx':2223,'xxxx':'333333']]
for row in range(len(produce_info_list2)):
for col in range(0, len(produce_info_list2[row])):
table.write(row + 1, col, produce_info_list2[row][col])
file.save(‘data.xls’)
import xlrd
data = xlrd.open_workbook('data.xls') #打开ecxel表
table = data.sheets()[0] #切换到对应的sheet
nrows = table.nrows #获取表格行数
with open("a.txt", "w") as f:
for i in range(1, nrows):
rows_values = table.row_values(i) #得到每一行的数据
for j in rows_values: #将每一行的数据写到txt文件中
f.write("{}
".format(j))
在原有excel表格中插入新的数据 code实现
思想: 复制原有的excel和sheet,获取行数,然后用新的表进行操作保存
import os
import re
import sys
import xlwt
import xlrd
from xlutils.copy import copy
import time
csv_cr_list = [[],[]]
class CWriteCSV(object):
'''
@Time : 2020/04/20 10:26:49
@Author : sunyan
@Desc : None'''
def __init__(self, excel_name):
self.data_path = None
self.excel_name = excel_name
self.CreateFolder()
self.file_handle = xlwt.Workbook() # 新建个文件
def CreateFolder(self):
'''
@Time : 2020/04/20 10:28:25
@功能 : None
'''
self.data_path = os.path.dirname(self.excel_name)
if self.data_path == "":
self.data_path = r'C:workpy3_codeStatisticalCRdata'
self.excel_name = f'{self.data_path}{self.excel_name}'
if not os.path.exists(self.data_path):
os.makedirs(self.data_path)
pass
def WriteLine(self, row_index, value_list, handel_, initial_value=None):
'''
@Time : 2020/04/27 07:43:28
@功能 : 写一行数据
'''
for index in range(len(value_list)):
# 在第i+1行和第j+1列写value(i、j从0开始)
handel_.write(row_index, index, value_list[index])
pass
def CreateXlsPage3(self, xls_data_list, keys_list=[], sheet_name="page1"):
'''
@Time : 2020/04/21 11:07:28
decs : None
'''
if not os.path.exists(self.excel_name):
sheet = self.file_handle.add_sheet(sheet_name, cell_overwrite_ok=True)
row_index = 0
self.WriteLine(row_index, keys_list, sheet)
row_index += 1
for value_list in xls_data_list:
self.WriteLine(row_index, value_list, sheet)
row_index += 1
self.Save()
else:
oldwb = xlrd.open_workbook(self.excel_name)
old_table = oldwb.sheets()[0]
nrows = old_table.nrows
newwb = copy(oldwb)
new_sheet = newwb.get_sheet(0)
for single_list in xls_data_list:
self.WriteLine(nrows,single_list,new_sheet)
nrows += 1
newwb.save(self.excel_name)
def Save(self, ):
'''
@Time : 2020/04/20 11:27:14
'''
self.file_handle.save(self.excel_name) # 保存成xls文件并指定文件名
pass
def main():
csv_keys = ['Account Nick Name', 'Case Number', 'Case Owner', 'Owner Region', 'Chipset',
'Case Type', 'Problem Area 1', 'Problem Area 2', 'Problem Area 3', 'comment_cr', 'Comment']
file_name = r'C:workpy3_codeStatisticalCRdataStatisticalCR.csv'
cws = CWriteCSV(file_name)
cws.CreateXlsPage3(csv_cr_list, csv_keys, sheet_name="Statistical_CR")
if __name__ == "__main__":
main()
注意:
在读取数据的时候可能会报“'ascii' codec can't encode character u'u201c' in position 124: ordinal not in range(128)”类似的错误
解决办法:在读取的文件开头加上如下代码
import sys
reload(sys)
sys.setdefaultencoding('utf-8')