python excel pandas openpyxl
1.遇到的問題
1.1、給帶公式的excel寫入數據,文件未保存狀態,讀值為None。
解決方式1:
from win32com.client import Dispatch # 使用win32com自動打開文件并保存 def just_open(filename): xlApp = Dispatch("Excel.Application") xlApp.Visible = False xlBook = xlApp.Workbooks.Open(filename) xlBook.Save() xlBook.Close() xlsx_name = r"D:\zmm\PC\PC_AT\performance.xlsx" just_open(xlsx_name) wb = load_workbook(xlsx_name, data_only=True) ws = wb['spec'] cell = ws["F60"] print(cell.value)
解決方式2:
import xlwings as xw
def xlsx_calculate(file_name): """ 使用 xlwings 打開 Excel 文件,并且對公式重新計算 :return: """ # # 需要重載一下這個文件,調整一下激活頁 # workbook = load_workbook(file_name) # workbook.active = 2 # for sheet in workbook: # if sheet.title == 'spec': # sheet.sheet_view.tabSelected = True # else: # sheet.sheet_view.tabSelected = False # workbook.save(file_name) app = xw.App(visible=False) workbook = app.books.open(file_name) # 1. 保證openpyxl做的修改保存到了文件 workbook.save() # # 2. 觸發所有公式重新計算 # workbook.app.calculate() # # 3. 保存公式計算后的結果 # workbook.save() # 4. 關閉 workbook.close() app.quit()
2.表格操作
2.1、寫入excel
pandas:
test_list = [temp.split() for temp in test_date] df1 = pd.DataFrame(test_list) with pd.ExcelWriter(xlsx_name, mode='a', engine="openpyxl", if_sheet_exists="replace") as writer: df1.to_excel(writer, sheet_name='stream', header=False, index=False)
openpyxl:
# 加載工作簿和工作表 wb = load_workbook(xlsx_name) ws = wb['spec'] cell = ws["D60"] cell.value = 10000 # 保存工作簿 wb.save(xlsx_name) wb.close()
2.2、讀取excel
pandas
p = pd.read_excel(xlsx_name, sheet_name="spec") spec_datas = p.to_dict(orient="records")
openpxl
wb = load_workbook(xlsx_name, data_only=True) ws = wb['spec'] cell = ws["F60"] print(cell.value)

浙公網安備 33010602011771號