search
HomeBackend DevelopmentPython Tutorialpython uses xlrd and xlwt to read, write and format excel

Recently, some problems occurred when using python to process excel tables, so I wanted to record the final implementation method and problem solving method. For your own convenience or for everyone to refer to when needed, the following article mainly introduces the relevant information on Python's use of xlrd and xlwt to read, write and format Excel. Let's learn together.

Preface

Python mainly uses the two libraries xlrd and xlwt to operate excel, that is, xlrd is a library for reading excel, and xlwt is a library for writing excel. This article mainly introduces python's use of xlrd and xlwt to read, write and format excel. Without further ado, let's take a look at the detailed implementation process.

Please indicate # in the script first -*- coding:utf-8 -*-

1. Confirm that the source excel exists and use xlrd to read the first The value in the first column of each row in a form.


import xlrd, xlwt 
import os 
 
assert os.path.isfile('source_excel.xls'),"There is no timesheet exist. Exit..." 
 
book = xlrd.open_workbook('source_excel.xls') 
sheet=book.sheet_by_index(0) 
 
for rows in range(sheet.nrows): 
 value = sheet.cell(rows,0).value


2. Use xlwt to prepare the data read from the source table and write it into the new table, and set the row width and The format of the table. After merging 2 rows and 8 columns of cells, write the title and set the format to title_style defined previously.

Use write_merge.


wbk = xlwt.Workbook(encoding='utf-8') 
sheet_w = wbk.add_sheet('write_after', cell_overwrite_ok=True) 
sheet_w.col(3).width = 5000 
tittle_style = xlwt.easyxf('font: height 300, name SimSun, colour_index red, bold on; align: wrap on, vert centre, horiz center;') 
sheet_w.write_merge(0,2,0,8,u'这是标题',tittle_style)


3. When using global variables in a function, be sure to add global. Otherwise, UnboundLocalError: local variable'xxx' referenced before assignment.


check_num = 0 
 
def check_data(sheet): 
 global check_num 
 check_num=check_num+1


4. Write date and formatted values. The original date format read from the sheet is 2014/4/10. After processing, only the date is retained and made into an array separated by commas and written into a new excel.


date_arr = [] 
date=sheet.cell(row,2).value.rsplit('/')[-1] 
if date not in date_arr: 
  date_arr.append(date) 
sheet_w.write_merge(row2,row2,6,6,date_num, normal_style) 
sheet_w.write_merge(row2,row2,7,7,','.join(date_arr), normal_style)


5. When the date format read from excel is xldate, you need to use xldate_as_tuple of xlrd to process it as date Format. First determine that the ctype of the table is indeed xldate before starting the operation, otherwise an error will be reported. The date format can then be converted to string using strftime. For example: date.strftime("%Y-%m-%d-%H")


##

from datetime import date,datetime 
from xlrd import xldate_as_tuple 
 
if (sheet.cell(rows,3).ctype == 3): 
  num=num+1 
  date_value = xldate_as_tuple(sheet.cell_value(rows,3),book.datemode) 
  date_tmp = date(*date_value[:3]).strftime("%d")


6. Finally save the newly written table


wbk.save('new_excel.xls')


More python uses xlrd and xlwt to read, write and format excel For related articles, please pay attention to 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
How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

How to solve the permissions problem encountered when viewing Python version in Linux terminal?How to solve the permissions problem encountered when viewing Python version in Linux terminal?Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

What are some popular Python libraries and their uses?What are some popular Python libraries and their uses?Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

Scraping Webpages in Python With Beautiful Soup: Search and DOM ModificationScraping Webpages in Python With Beautiful Soup: Search and DOM ModificationMar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

How to Create Command-Line Interfaces (CLIs) with Python?How to Create Command-Line Interfaces (CLIs) with Python?Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft