python3 讀寫excel文件

直接上代碼: 

import xlrd
import xlwt

import datetime
#導入需要讀取的第一個Excel表格的路徑
data1 = xlrd.open_workbook(r'test.xlsx')
table = data1.sheets()[0]

#創建一個空列表,存儲Excel的數據
tables = []

#將excel表格內容導入到tables列表中
def import_excel(excel):
  for rown in range(excel.nrows):
   array = {'road_name':'','bus_plate':'','timeline':'','road_type':'','site':''}
   array['road_name'] = table.cell_value(rown,0)
   array['bus_plate'] = table.cell_value(rown,1)
   if table.cell(rown,2).ctype == 3:
     date = xldate_as_tuple(table.cell(rown,2).value,0)
     array['timeline'] = datetime.datetime(*date)
   array['road_type'] = table.cell_value(rown,3)
   array['site'] = table.cell_value(rown,4)
   tables.append(array)
if __name__ == '__main__':
  #將excel表格的內容導入到列表中
  import_excel(table)
  for i in tables:
    print(i)
  

  # 輸出
  book = xlwt.Workbook(encoding = 'utf-8') #創建一個Excel對象
  sheet1 = book.add_sheet('sheet1') #添加一個名爲sheet1的sheet
  style = xlwt.XFStyle()
  sheet1.write(i, j, content) #在索引爲i, j處寫入content
  book.save("output.xls") # 保存


main()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章