Xlrd module in Python and use xlwt ---- "" derived database data (one)

xlrd module for the reading of the excel file content, xlwt module realized on the excel file.

 

 

(1) Open excel file and get all sheet

>>> import xlrd
>>> workbook = xlrd.open_workbook(r'D:\Program Files\Notepad++\Student.xlsx')
>>> print workbook.sheet_names()
[u'Sheet1', u'Sheet2', u'Sheet3']

(2) The name of the acquired sheet subscript

>>> sheet2_name=workbook.sheet_names()[1]
>>> print sheet2_name
Sheet2

(3) The content acquisition sheet or index sheet name, sheet name acquired simultaneously, the number of rows, the number of columns.

>>> sheet2 = workbook.sheet_by_index(1)
>>> print sheet2.name,sheet2.nrows,sheet2.ncols
Sheet2 6 5
>>> sheet2 = workbook.sheet_by_name('Sheet2')
>>> print sheet2.name,sheet2.nrows,sheet2.ncols
Sheet2 6 5

(4) Get value of whole rows and columns in accordance with the sheet name

>>> sheet2 = workbook.sheet_by_name('Sheet2')
>>> rows = sheet2.row_values(3)
>>> cols = sheet2.col_values(2)
>>> print rows
[U ' lisi2 ' , 19.0, 41462.0, U ' Basketball ' , U ' FRIEND2 ' ] # marked red part of the date 2013/7/7, but the actual display is floating. Followed by a description of how to correct 
>>> Print cols
[U ' \ u51fa \ u751f \ u65e5 \ u671f ' , 42129.0, 41796.0, 41462.0, 40941.0, U '' ] # issue Ibid 
>>>

(5) obtaining the specified content of the cells

Copy the code
>>> print sheet2.cell(1,0).value.encode('utf-8')
xiaoming2
>>> print sheet2.cell_value(1,0).encode('utf-8')
xiaoming2
>>> print sheet2.row(1)[0].value.encode('utf-8')
xiaoming2
Copy the code

(6) acquiring the data type of the cell contents

Copy the code
>>> print sheet2.cell (1,0) .ctype # row 2, column 1: xiaoming2 type string
1
>>> print sheet2.cell (1,1) .ctype # row 2, column 2: number of type 12
2
>>> print sheet2.cell (1,2) .ctype # row 2, column 3: is date 2015/5/5
3
Copy the code

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

(7) Content acquisition unit type date manner

   The use xlrd xldate_as_tuple date format is processed, first determine the table when xlrd ctype = 3 to perform operations as follows:

Copy the code
>>> from datetime import datetime,date
>>> sheet2.cell(1,2).ctype
3
>>> sheet2.cell(1,2).value
42129.0
>>> xlrd.xldate_as_tuple(sheet2.cell_value(1,2),workbook.datemode)
(2015, 5, 5, 0, 0, 0)
>>> date_value = xlrd.xldate_as_tuple(sheet2.cell_value(1,2),workbook.datemode)
>>> date(*date_value[:3])
datetime.date(2015, 5, 5)
>>> date(*date_value[:3]).strftime('%Y/%m/%d')
'2015/05/05'
Copy the code

If it needs to acquire the script and the display contents of the cell type to date, you can do a judgment. Ctype is equal to 3 is determined, and if equal to 3, then the processing time format:

if (sheet.cell(row,col).ctype == 3):
  date_value = xlrd.xldate_as_tuple(sheet.cell_value(row,col),book.datemode)
  date_tmp = date(*date_value[:3]).strftime('%Y/%m/%d')

(8) obtaining a merged cell content

Copy the code
>>> sheet2.cell (1,4) .value # lines 2 and row 3, 4 are merged cell
u'friend'
>>> sheet2.cell(2,4).value
in the ''
Column 2 >>> sheet2.cell (5,1) .value # line 6 and the third and fourth are merged cell, here we only obtain the value at row 6, column 2 and column 3 4 Gets contents of the column is empty, how to deal with?
u'None'
>>> sheet2.cell(5,2).value
in the ''
>>> sheet2.cell(5,3).value
in the ''
Copy the code

   Can be seen from the test results came out, the second column of the line 6 and the third and fourth are merged cell, but here we only obtain the value at row 6, column 2 and column 3 the contents of the four acquired empty theoretically speaking merger

Cell contents should be the same, but now only the first cell of the merged can get to the value of the other is empty, how to deal with? And then display a more intuitive way

>>> sheet2.row_values(5)
[u'zhaoliu2 ', u'None', U '', U '', U '' ] # marked red part of a merged cell
>>> sheet2.col_values(4)
[U '\ u5173 \ u7cfb', u'friend ', U' ' , u'friend2', U '' , U ''] part of a merged cell # marked red, note here two merged cells

  Can be treated with merged_cells method, processing method is the index ranks only get merged cells in the first cell in order to read the value read wrong is null. That row merge read cell

The first index of the row, reads the first column of cells merge a column index. Here, you need to add the time to read the file parameters, the formatting_info parameter is set to True, the default is False, No

It may call merged_cells method to get to a null value.

Copy the code
>>> workbook = xlrd.open_workbook(r'D:\Program Files\Notepad++\Student.xlsx',formatting_info=True) 

>>> sheet2 = workbook.sheet_by_name('sheet2')

>>> sheet2.merged_cells
[(1, 3, 4, 5), (3, 5, 4, 5), (5, 6, 1, 5)]
Copy the code

The meaning of these four parameters merged_cells returns: (row, row_range, col, col_range), wherein [row, row_range) comprises a row, not including row_range, col is the same, from 0 to open the subscript

beginning. I.e. (1, 3, 4, 5) the meaning: 2 to 3 rows (not including the fourth row) were combined, (5, 6, 1, 5) the meaning: of 2-5 combined. With this, it is possible to obtain three cells incorporated are:

Copy the code
>>> print sheet2.cell_value(1,4) #(1, 3, 4, 5)
friend
>>> print sheet2.cell_value(3,4) #(3, 5, 4, 5)
friend2
>>> print sheet2.cell_value(5,1) #(5, 6, 1, 5)
None
Copy the code

It found that the law did not? Yes, I get to row and col index low of merge_cells returned ! So can this once and for all:

Copy the code
>>> merge = []
>>> for (rlow,rhigh,clow,chigh) in sheet2.merged_cells:
...   merge.append([rlow,clow])
...
>>> merge
[[1, 4], [3, 4], [5, 1]]
>>> for index in merge:
...   print sheet2.cell_value(index[0],index[1])
...
friend
friend2
None
Copy the code

xlwt module

Suppose you want to achieve the following written excel, how

 

code show as below:

Copy the code
'''
Set cell style
'''
 
def set_style(name,height,bold=False):
  style = xlwt.XFStyle () # initialize style
 
  font = xlwt.Font () # Create a font style
  font.name = name # 'Times New Roman'
  font.bold = bold
  font.color_index = 4
  font.height = height
 
  # borders= xlwt.Borders()
  # borders.left= 6
  # borders.right= 6
  # borders.top= 6
  # borders.bottom= 6
 
  style.font = font
  # style.borders = borders
 
  return style
 
 
# Write excel
def write_excel():
  f = xlwt.Workbook () # Create a workbook
 
  '''
  Create the first sheet:
    sheet1
  '''
  sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True) #创建sheet
  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 'Reserve', u 'ticket', u 'refund', u 'business Subtotal']
 
  # Create the first line
  for i in range(0,len(row0)):
    sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True))
 
  And generating a first column # last column (4 rows combined)
  i, j = 1, 0
  while i < 4*len(column0) and j < len(column0):
    sheet1.write_merge(i,i+3,0,0,column0[j],set_style('Arial',220,True)) #第一列
    sheet1.write_merge (i, i + 3,7,7) # finally a "Total"
    i += 4
    j += 1
 
  sheet1.write_merge(21,21,0,1,u'合计',set_style('Times New Roman',220,True))
 
  # Generate a second column
  i = 0
  while i < 4*len(column0):
    for j in range(0,len(status)):
      sheet1.write(j+i+1,1,status[j])
    i += 4
 
  f.save ( 'demo1.xlsx') # Save the file
 
if __name__ == '__main__':
  #generate_workbook()
  #read_excel()
  write_excel()
Copy the code

It needs a little explanation is write_merge method:

write_merge (X, X + m, y, + n-W, string, sytle)
X represents a row, y denotes a column, m represents a number interbank, n represents the number of columns across, string showing the content of the cell to be written, style It represents the cell style. Wherein, x, y, w, h , are counted to 0

of.

And reading the merged cell is not the same in xlrd.

As described above: sheet1.write_merge (21,21,0,1, u 'total', set_style ( 'Times New Roman', 220, True))

即在22行合并第1,2列,合并后的单元格内容为"合计",并设置了style。

如果需要创建多个sheet,则只要f.add_sheet即可。

如在上述write_excel函数里f.save('demo1.xlsx') 这句之前再创建一个sheet2,效果如下:

 

代码也是真真的easy的了:

Copy the code
'''
  创建第二个sheet:
    sheet2
  '''
  sheet2 = f.add_sheet(u'sheet2',cell_overwrite_ok=True) #创建sheet2
  row0 = [u'姓名',u'年龄',u'出生日期',u'爱好',u'关系']
  column0 = [u'小杰',u'小胖',u'小明',u'大神',u'大仙',u'小敏',u'无名']
 
  #生成第一行
  for i in range(0,len(row0)):
    sheet2.write(0,i,row0[i],set_style('Times New Roman',220,True))
 
  #生成第一列
  for i in range(0,len(column0)):
    sheet2.write(i+1,0,column0[i],set_style('Times New Roman',220))
 
  sheet2.write(1,2,'1991/11/11')
  sheet2.write_merge(7,7,2,4,u'暂无') #合并列单元格
  sheet2.write_merge (1,2,4,4, u 'friend') merged row of the cell #
   
  f.save ( 'demo1.xlsx') # Save the file
Copy the code

Guess you like

Origin www.cnblogs.com/xiaozengzeng/p/11932899.html