
条件1:如果第二列的单元格数据第1位为3,则该单元格数据末尾添加一个字母A
条件2:如果第二列的单元格数据第1位为4,则该单元格数据末尾添加一个字母B
条件3:如果第二列的单元格数据第1位为5,则该单元格数据首位添加一个字母C
条件4:如果第二列的单元格数据第2位为6,则该单元格数据第3位添加一个字母D
刚学python,我想用python处理excel的数据,遇到上面的情况就不知道怎么处理,卡了很久了,求帮忙
import xlwt # 写
# pip3 install xlwt
import xlrd # 读
# pip3 install xlrd==1.2.0 # 指定版本,解决XLRDError: Excel xlsx file; not supported
# https://ask.csdn.net/questions/7759120
# 条件1:如果第二列的单元格数据第1位为3,则该单元格数据末尾添加一个字母A
# 条件2:如果第二列的单元格数据第1位为4,则该单元格数据末尾添加一个字母B
# 条件3:如果第二列的单元格数据第1位为5,则该单元格数据首位添加一个字母C
# 条件4:如果第二列的单元格数据第2位为6,则该单元格数据第3位添加一个字母D
src_xls = '~/Desktop/test.xls'
dst_xls = '~/Desktop/test_2.xls'
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('表')
book = xlrd.open_workbook(src_xls, formatting_info=True) # 加载文件
# sheets = book.sheet_names() # 全部工作表的名称
sheet = book.sheet_by_index(0) # 打开表
rows = sheet.nrows # 行数
cols = sheet.ncols # 列数
# for row in sheet.get_rows():
# for cell in row:
# print(cell)
for i in range(0, rows): # 遍历全部的行
row = sheet.row(i) # 得到某行全部的列,即此行全部单元格 list<Cell>
for j in range(0, cols): # 遍历每行全部的单元格
cell = row[j].value # 某格的内容
if 1==j: # 目标列
cell = str(cell) # 默认单元格属性是数字,会默认添加一个".0"的尾巴
cell = cell.split(".")[0] # 去掉尾巴
new_cell = cell
char_2 = cell[1] # 数据第2位
if "6" == char_2: # 为6,则数据第[3]位添加一个字母D
# left = new_cell[0:2:1] # 从索引0开始取,取到索引2,步长1
left = new_cell[:2:]
right = new_cell[2::] # 从索引3开始取,取到末尾,步长1
new_cell = left + "D" + right
char_1 = cell[0] # 数据第1位
if "3" == char_1: # 为3,则数据末尾添加一个字母A
new_cell = new_cell + "A"
if "4" == char_1: # 为4,则数据末尾添加一个字母B
new_cell = new_cell + "B"
if "5" == char_1: # 为5,则数据[首位]添加一个字母C
new_cell = "C" + new_cell
worksheet.write(i, j, new_cell) # 缓存指定单元格数据
else:
worksheet.write(i, j, cell)
workbook.save(dst_xls) # 保存到文件
df=pd.DataFrame({'A':[1,2,3,4,5,1],'B':[356,444,766,3666,123,40]})
df.B=df.B.map(str).str.replace(r'(^[3].*)',r'\1A',regex=True).replace(r'(.)(6)(.*)',r'\1\2D\3',regex=True)
print(df)
这篇文章:
Python设置excel单元格格式 也许有你想要的答案,你可以看看