Mac——利用Python讀取與寫入Excel文檔
目的:按照自定義的格式寫入或讀取Excel文檔,如標紅加粗等
Python代碼:
import xlwt
import pandas as pd
def save_excel_way1():
# 創建Excel文件
wb = xlwt.Workbook()
ws = wb.add_sheet('keyword_extract')
# 保存爲excel文檔
# 紅色加粗格式
font0 = xlwt.Font()
# font0.name = 'Times New Roman'
font0.colour_index = 2
font0.bold = True
style0 = xlwt.XFStyle()
style0.font = font0
# 黑體加粗
font1 = xlwt.Font()
font1.name = '黑體'
font1.bold = True
style1 = xlwt.XFStyle()
style1.font = font1
# 自動換行
style = xlwt.XFStyle() # 初始化樣式
style.alignment.wrap = 1 # 自動換行
ws.write(0, 0, "地區", style0)
ws.write(0, 1, "屬性", style0)
ws.write(1, 0, "中國", style0)
ws.write(1, 1, "加油1", style0)
ws.write(2, 0, "武漢", style1)
ws.write(2, 1, "加油2", style1)
wb.save("res.xls") # 保存爲Excel文檔
def load_excel():
data = pd.read_excel("res.xls", sheet_name='keyword_extract', usecol=[0, 1], header=None) # 讀取Excel文檔
print(data.head()) # 顯示錶格
# 獲取最大行,最大列
rows = data.shape[0]
cols = data.columns.size
print("\n行:", rows, "列:", cols)
# 取值
print(data[1][2]) # 特定單元格
print(data[1]) # 某列
print(data.iloc[1]) # 某行
if __name__ == "__main__":
save_excel_way1()
load_excel()
輸出:
0 1
0 地區 屬性
1 中國 加油1
2 武漢 加油2
行: 3 列: 2
加油2
0 屬性
1 加油1
2 加油2
Name: 1, dtype: object
0 中國
1 加油1
Name: 1, dtype: object
說明:Pandas的寫入操作參考以前的文章利用Python處理常見文件
參考博客: