Home>Article>Backend Development> How does python handle tables?
How does python handle tables?
How to process tables in python:
Python mainly uses the two libraries xlrd and xlwt to operate excel, that is, xlrd is for reading excel, and xlwt is for writing excel library. It can be downloaded from https://pypi.python.org/pypi. The following records respectively python reading and writing excel.
Writing excel in Python——xlwt
The difficulty in writing excel in Python is not the construction of a workbook itself, but the data filled in, but this is not within the scope. There are also thorny problems in writing excel. For example, writing merged cells is more troublesome, and there are different writing styles.
The detailed code is as follows:
import xlwt #设置表格样式 def set_style(name,height,bold=False): style = xlwt.XFStyle() font = xlwt.Font() font.name = name font.bold = bold font.color_index = 4 font.height = height style.font = font return style #写Excel def write_excel(): f = xlwt.Workbook() sheet1 = f.add_sheet('学生',cell_overwrite_ok=True) row0 = ["姓名","年龄","出生日期","爱好"] colum0 = ["张三","李四","恋习Python","小明","小红","无名"] sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True)) #写第一列 for i in range(0,len(colum0)): sheet1.write(i+1,0,colum0[i],set_style('Times New Roman',220,True)) sheet1.write(1,3,'2006/12/12') sheet1.write_merge(6,6,1,3,'未知')#合并行单元格 sheet1.write_merge(1,2,3,3,'打游戏')#合并列单元格 sheet1.write_merge(4,5,3,3,'打篮球') f.save('test.xls') if __name__ == '__main__': write_excel()
Result diagram:
Here, a brief explanation of the usage of write_merge(), as mentioned above :sheet1.write_merge(1,2,3,3,'playing games'), that is, merging the 2nd and 3rd columns in four columns. The merged cell content is "total" and the style is set. Among them, all parameters are calculated starting from 0.
Python reads excel - xlrd
Python reads Excel tables. Compared with xlwt, xlrd provides more interfaces, but the process also has several troublesome problems, such as reading Date, read merged cell contents.
Let’s take a look at the basic operations:
The overall idea is to open the file, select the table, read the rows and columns, and read the data in the table
The detailed code is as follows:
import xlrd from datetime import date,datetime file = 'test3.xlsx' def read_excel(): wb = xlrd.open_workbook(filename=file)#打开文件 print(wb.sheet_names())#获取所有表格名字 sheet1 = wb.sheet_by_index(0)#通过索引获取表格 sheet2 = wb.sheet_by_name('年级')#通过名字获取表格 print(sheet1,sheet2) print(sheet1.name,sheet1.nrows,sheet1.ncols) rows = sheet1.row_values(2)#获取行内容 cols = sheet1.col_values(3)#获取列内容 print(rows) print(cols) print(sheet1.cell(1,0).value)#获取表格里的内容,三种方式 print(sheet1.cell_value(1,0)) print(sheet1.row(1)[0].value)
The running results are as follows:
Then the question comes. In the above running results, the red box The field is clearly the date of birth, and the actual floating point number that can be displayed; at the same time, there should be content in the merged cells, and the result cannot be empty.
Don’t worry, let’s solve these two problems one by one:
1. How python reads the cell content in excel as date
Python reads excel There are 5 types of cell content returned, namely ctype in the above example:
ctype: 0 empty, 1 string, 2 number, 3 date, 4 boolean, 5 error
That is The ctype of date=3. In this case, you need to use xlrd's xldate_as_tuple to process it into date format. Only when the ctype=3 of the table is determined can xldate start the operation.
The detailed code is as follows:
import xlrd from datetime import date,datetime print(sheet1.cell(1,2).ctype) date_value = xlrd.xldate_as_tuple(sheet1.cell_value(1,2),wb.datemode) print(date_value) print(date(*date_value[:3])) print(date(*date_value[:3]).strftime('%Y/%m/%d'))
2. Get the contents of merged cells
Before operating, let’s introduce merged_cells() Usage, the meaning of the four parameters returned by merged_cells is: (row, row_range, col, col_range), where [row, row_range] includes row, does not include row_range, and the same is true for col, that is, (1, 3, 4, 5) The meaning of (7, 8, 2, 5) is: merge rows 1 to 2 (excluding 3), and the meaning of (7, 8, 2, 5) is: merge columns 2 to 4.
The detailed code is as follows:
print(sheet1.merged_cells)print(sheet1.cell_value(1,3)) print(sheet1.cell_value(4,3)) print(sheet1.cell_value(6,1))
Have you found the pattern? Yes, just get the low index of row and col returned by merge_cells! So you can get it in batches like this:
The detailed code is as follows:
merge = [] print(sheet1.merged_cells) for (rlow,rhigh,clow,chigh) in sheet1.merged_cells: merge.append([rlow,clow]) for index in merge: print(sheet1.cell_value(index[0],index[1]))
The running result is the same as the picture above, as follows:
Recommended tutorial: 《python》
The above is the detailed content of How does python handle tables?. For more information, please follow other related articles on the PHP Chinese website!