如何修改已經存在的excel表中的單個值呢?
主要思路:修改已存在的excel表馋记,需要用到xlutils中copy()方法号坡,將原有的表格拷貝一份,在進行寫操作梯醒,然后將修改后的表移動到原來的位置宽堆,覆蓋原有的表,進行保存
前提準備:
1.先pip安裝xlutils : >>pip install xlutils
操作步驟:
1.導入要用到的模塊
from xlutils.copy import copy
import xlrd
import os
2.拷貝舊表
old_excel = xlrd.open_workbook(excel_path)
new_excel = copy(old_excel)
3.獲取到第一個sheet頁
sheet = new_excel.get_sheet(0)
4.修改單元格的值
sheet.write(0,0, '哈哈') # 將第一行第一列修改為“哈哈”
5.將文件移動到指定路徑上茸习,并保存(這里兩處路徑都要與原來的excel存放地址保持一致)
os.remove('xxxxxx')
self.new_excel.save('xxxxxx')
下面是我寫的一個完整的修改已存在excel的類:
from xlutils.copy import copy
import xlrd
import os
# excel的存放路徑
excel_path = r'C:\Users\zd\Desktop\test.xls'
class ExcelUpdate(object):
def __init__(self):
self.old_excel = xlrd.open_workbook(excel_path)
self.new_excel = copy(self.old_excel)
def update_value(self, cell, value):
'''
- cell: 傳入一個單元格坐標參數(shù)畜隶,例如:cell=(0,0),表示修改第一行第一列
'''
sheet = self.new_excel.get_sheet(0)
sheet.write(*cell, value)
os.remove(excel_path)
self.new_excel.save(excel_path)
def update_values(self, cells, values):
'''
- cells: 傳入一個單元格坐標參數(shù)的list,
- values: 傳入一個修改值的list号胚,
例如:cells = [(0, 0), (0, 1)],values = ('a', 'b')
表示將列表第一行第一列和第一行第二列籽慢,分別修改為 a 和 b
'''
for i in range(len(cells)):
self.update_value(cells[i], values[i])
if __name__ == '__main__':
start = ExcelUpdate()
cells1 = [(0, 0), (0, 1)]
values1 = ('飛豬', '哈哈')
start.update_values(cells1, values1)