search
HomeBackend DevelopmentPython TutorialHow does python handle tables?

How does python handle tables?

Jun 10, 2020 pm 03:37 PM
pythonsheet

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:

How does python handle tables?

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:

How does python handle tables?

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:

How does python handle tables?

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'))

How does python handle tables?

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))

How does python handle tables?

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:

How does python handle tables?

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

How can you make a Python script executable on both Unix and Windows?How can you make a Python script executable on both Unix and Windows?May 06, 2025 am 12:13 AM

TomakeaPythonscriptexecutableonbothUnixandWindows:1)Addashebangline(#!/usr/bin/envpython3)andusechmod xtomakeitexecutableonUnix.2)OnWindows,ensurePythonisinstalledandassociatedwith.pyfiles,oruseabatchfile(run.bat)torunthescript.

What should you check if you get a 'command not found' error when trying to run a script?What should you check if you get a 'command not found' error when trying to run a script?May 06, 2025 am 12:03 AM

When encountering a "commandnotfound" error, the following points should be checked: 1. Confirm that the script exists and the path is correct; 2. Check file permissions and use chmod to add execution permissions if necessary; 3. Make sure the script interpreter is installed and in PATH; 4. Verify that the shebang line at the beginning of the script is correct. Doing so can effectively solve the script operation problem and ensure the coding process is smooth.

Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor