python學習,excel操作之xlsxwriter常用操作
阿新 • • 發佈:2019-02-18
xlsx mat 學習 常用操作 bsp one ota foo number
from datetime import datetime import xlsxwriter #打開文件 workbook = xlsxwriter.Workbook(‘Expenses03.xlsx‘) worksheet = workbook.add_worksheet() #設置粗體格式 bold = workbook.add_format({‘bold‘: 1}) #設置錢幣格式 money_format = workbook.add_format({‘num_format‘: ‘$#,##0‘}) #設置日期格式 date_format = workbook.add_format({‘num_format‘: ‘mmmm d yyyy‘}) #設置寬度 worksheet.set_column(1, 1, 15) #寫入數據 # worksheet.write(‘A1‘, ‘Item‘, bold) # worksheet.write(‘B1‘, ‘Date‘, bold) # worksheet.write(‘C1‘, ‘Cost‘, bold) worksheet.write_row(‘A1‘,["Item","Date","Cost"],bold) #需要寫入的數據 expenses = ( [‘Rent‘, ‘2013-01-13‘, 1000], [‘Gas‘, ‘2013-01-14‘, 100], [‘Food‘, ‘2013-01-16‘, 300], [‘Gym‘, ‘2013-01-20‘, 50], ) #寫入數據開始位置 row = 1 col = 0 for item, date_str, cost in (expenses): #將日期格式轉為日期對象 date = datetime.strptime(date_str, "%Y-%m-%d") worksheet.write_string(row, col, item) worksheet.write_datetime(row, col + 1, date, date_format) worksheet.write_number(row, col+ 2, cost, money_format) row += 1 #寫入統計總數公式 worksheet.write(row, 0, ‘Total‘, bold) worksheet.write(row, 2, ‘=SUM(C2:C5)‘, money_format) workbook.close()
python學習,excel操作之xlsxwriter常用操作