0%

python利用xlutils在已存在xls文件继续修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import xlrd  # 导入模块
from xlutils.copy import copy # 导入copy模块

class EditExcel():

def __init__(self, path, sheet_name):
self.path = path
self.sheet_name = sheet_name

def get_excel_sheet(self):
# 打开excel
read_open_xls = xlrd.open_workbook(self.path)
# 得到excel中的sheet_name
read_xlsx_sheet = read_open_xls.sheet_by_name(self.sheet_name)
# 拷贝excel
copy_book = copy(read_open_xls)
return copy_book, read_xlsx_sheet,

def write_value(self):
copy_book, read_xlsx_sheet = self.get_excel_sheet()
# 获取行数
row_max = read_xlsx_sheet.nrows
# 获取第一行的值
rows = read_xlsx_sheet.row_values(0)
# 获取列数
col_max = read_xlsx_sheet.ncols
for row in range(row_max):
row_value = read_xlsx_sheet.row_values(row)
for col in range(col_max):
current_value = read_xlsx_sheet.cell(row, col).value
# 按照条件过滤
if current_value == 'Pass':
copy_sheet = copy_book.get_sheet(0)
copy_sheet.write(row, col, '11111')
copy_book.save(self.path)


EditExcel("test.xls", "Sheet1").write_value()

注意

  • 不支持xlsx文件的修改,只支持xls