Home Backend Development Python Tutorial How does python handle tables?

How does python handle tables?

Jun 10, 2020 pm 03:37 PM
python sheet

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()
Copy after login

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)
Copy after login

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'))
Copy after login

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))
Copy after login

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]))
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles