Python simple way to read and write Excel table

  Install two libraries: pip install xlrd, pip install xlwt

  1.python read excel - xlrd

  2.python write excel - xlwt

  1. Read excel data, including date data

  #coding=utf-8

  import xlrd

  import datetime

  from datetime import date

  def read_excel():

  #open a file

  wb = xlrd.open_workbook(r'test.xlsx')

  # Get the names of all sheet

  print(wb.sheet_names())

  # Gets the second sheet showed

  sheet2 = wb.sheet_names()[1]

  # Sheet1 index from zero, get a handle on sheet1 table

  sheet1 = wb.sheet_by_index(0)

  rowNum = sheet1.nrows

  colNum = sheet1.ncols

  #s = sheet1.cell(1,0).value.encode('utf-8')

  s = sheet1.cell(1,0).value

  # Obtain a certain location data

  # 1 ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

  print(sheet1.cell(1,2).ctype)

  print(s)

  #print(s.decode('utf-8'))

  # Get Data whole rows and columns

  # The second line data

  row2 = sheet1.row_values(1)

  # The second column data

  cols2 = sheet1.col_values(2)

  #python excel in reading the cell contents of the date mode

  # There are five types of return

  for i in range(rowNum):

  if sheet1.cell(i,2).ctype == 3:

  d = xlrd.xldate_as_tuple(sheet1.cell_value(i,2),wb.datemode)

  print(date(*d[:3]),end='')

  print('\n')

  if __name__ == '__main__':

  read_excel()~

  running result

  2. To write data to excel

  #coding=utf-8

  import xlwt

  # Set the Table Style

  def set_stlye(name,height,bold=False):

  # Initialize style

  style = xlwt.XFStyle()

  # Create font

  font = xlwt.Font ()

  font.bold = bold

  font.colour_index = 4

  font.height = height

  font.name =name

  style.font = font

  return style

  #data input

  def write_excel():

  f = xlwt.Workbook()

  # Create sheet1 Zhengzhou flow of the hospital http://mobile.zzzzyy120.com/

  sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True)

  row0 = [u 'business', u 'state', u 'Beijing', u 'Shanghai', u 'Canton', u 'Shenzhen', u 'state Subtotal', u 'total']

  column0 = [u 'tickets', u 'tickets', u 'train', u 'bus ticket', u 'other']

  status = [u 'predetermined', u 'ticket', u 'refund', u 'business Subtotal']

  for i in range(0,len(row0)):

  sheet1.write(0,i,row0[i],set_stlye("Time New Roman",220,True))

  i,j = 1,0

  while i <4 * len (column0): # control loop: 4 each plus

  #first row

  sheet1.write_merge(i,i+3,0,0,column0[j],set_stlye('Arial',220,True))

  #last row

  sheet1.write_merge(i,i+3,7,7)

  i += 4

  sheet1.write_merge(21,21,0,1,u'合计',set_stlye("Time New Roman",220,True))

  i=0

  while i <4 * len (column0): # control outer loop: each plus 4

  for j in range (0, len (status)): # the inner control loop: setting contents of each line

  sheet1.write(i+j+1,1,status[j])

  i += 4

  # Create sheet2

  sheet2 = f.add_sheet(u'sheet2',cell_overwrite_ok=True)

  row0 = [u 'name', u 'Age', u 'date of birth', u 'hobby', u 'relationship']

  column0 = [u'UZI ', u'Faker', u 'Sima', u'PDD ', u' von Timo ']

  # Create the first line

  for i in range(0,len(row0)):

  sheet2.write(0,i,row0[i],set_stlye('Times New Roman',220,True))

  # Generate a first column

  for i in range(0,len(column0)):

  sheet2.write(i+1,0,column0[i],set_stlye('Times New Roman',220,True))

  f.save('data.xls')

  if __name__ == '__main__':

  write_excel()~

  In data.xls species generated sheet1 and sheet2


Guess you like

Origin blog.51cto.com/14335413/2459549