Home Backend Development Python Tutorial python XlsxWriter module creates aexcel table

python XlsxWriter module creates aexcel table

May 04, 2018 pm 03:45 PM
python xlsxwriter

这篇文章主要介绍了关于python XlsxWriter模块创建aexcel表格,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

安装使用pip install XlsxWriter来安装,Xlsxwriter用来创建excel表格,功能很强大,下面具体介绍:

1.简单使用excel的实例:

#coding:utf-8
import xlsxwriter

workbook = xlsxwriter.Workbook('d:\\suq\\test\\demo1.xlsx') #创建一个excel文件
worksheet = workbook.add_worksheet('TEST') #在文件中创建一个名为TEST的sheet,不加名字默认为sheet1
 
worksheet.set_column('A:A',20) #设置第一列宽度为20像素
bold = workbook.add_format({'bold':True}) #设置一个加粗的格式对象
 
worksheet.write('A1','HELLO') #在A1单元格写上HELLO
worksheet.write('A2','WORLD',bold) #在A2上写上WORLD,并且设置为加粗
worksheet.write('B2',U'中文测试',bold) #在B2上写上中文加粗
 
worksheet.write(2,0,32) #使用行列的方式写上数字32,35,5
worksheet.write(3,0,35.5) #使用行列的时候第一行起始为0,所以2,0代表着第三行的第一列,等价于A4
worksheet.write(4,0,'=SUM(A3:A4)') #写上excel公式
worksheet.insert_image('B5','f:\\1.jpg') #插入一张图片
 
workbook.close()
Copy after login

2.常用方法说明

1.Workbook类

Workbook类创建一个XlsxWriter的Workbook对象,代表整个电子表格文件,存储到磁盘上.

add_worksheet():用来创建工作表,默认为sheet1

add_format():创建一个新的格式对象来格式化单元格,例如bold=workbook.add_format({'bold':True})

还可以使用set_bold,例如:bold=workbook.add_format() bold.set_bold()

#border:边框,align:对齐方式,bg_color:背景颜色,font_size:字体大小,bold:字体加粗
top = workbook.add_format({'border':1,'align':'center','bg_color':'cccccc','font_size':13,'bold':True})
Copy after login

add_chart(options):创建一个图表对象,内部是使用insert_chart()方法来实现的,options(dict类型)为图表指定一个字典属性

close():关闭文件

2.Worksheet类

worksheet代表一个Excel的工作表,是XlsxWriter的核心,下面是几个核心方法

write(row,col,*args):写普通数据到工作表的单元格,row行坐标,col列坐标,起始都是以0开始,*args为写入的内容,可以是字符串,文字,公式等,writer方法已经作为其它更具体数据类型方法的别名

write_string():写入字符串类型,worksheet.write_string(0,0,'your text')

write_number():写入数字类型,worksheet.write_number('A2',1.1)

write_blank():写入空类型数据,worksheet.write_blank('A2',None)

wirte_formula():写入公式类型,worksheet.write_formula(2,0,'=SUM(B1:B5))

write_datetime():写入日期类型数据,worksheet.write_datetime(7,0,datetime.datetime.strptime('2014-01-02','%Y-%m-%d),workbook.add_format({'num_format':'yyyy-mm-dd'}));

write_boolean():写入逻辑类数据,worksheet.write_boolean(0,0,True)

write_url():写入超链接类型数据,worksheet.write_url('A1','ftp://www.python.org')

write_column():写入到一列,后面接一个数组

wirte_row():写入到一行,后面接一个数组

set_row(row,height,cell_format,options):此方法设置行单元格的属性,row指定行位置,height指定高度,单位是像素,cell_format

指定格式对象,参数options设置hiddeen(隐藏),level(组合分级),collapsed(折叠,例如:

cell_format=workbook.add_format({'bold':True})

worksheet.set_row(0,40,cell_format) 设置第一行高40,加粗

set_column(first_col,last_col,width,cell_format,options):

设置列单元格的属性,具体参数说明如上.worksheet.set_column(0,1,10) worksheet.set_column('C:D',20)

insert_image(row,col,image[,options]):此方法是插入图片到指定单元格

例如插入一个图片的超链接为www.python.org

worksheet.insert_image('B5','f:\\1.jpg',{'url':'http://www.python.org'})

3.Chart类

Chart类实现XlsxWriter模块中的图标组件的基类,支持的图表类型包括面积,条形图,柱形图,折形图,饼图,散点图,股票和雷达. 一个图表对象是通过Workbook的add_chart方法创建,通过{type,'图表类型'}字典参数指定图表的类型,语句如下:

chart = workbook.add_chart({type,'column'}) #创建一个column图表

更多图表类型说明:

area:创建一个面积样式的图表;

bar:创建一个条形样式的图表;

column:创建一个柱形样式的图表;

line:创建一个线条样式的图表

pie:创建一个饼图样式的图表

scatter:创建一个散点样式的图表

stock:创建一个股票样式的图表;

radar:创建一个雷达央视的图表

然后通过insert_chart()方法插入到指定的位置,语句如下:

worksheet.insert_chart('A7',chart)
Copy after login

chart.add_series(options)方法,作用是添加一个数据系列到图表,参数options(dict类型)设置图表系列选项的字典,操作示例如下:

chart.add_series({
'categories':'=Sheet1!$A$$1:$A$5',
'values':'=Sheet1!$A$$1:$A$5',
'line':={'color':'red'}
})
Copy after login

categories,values,line最为常用,categories作用是设置图表类别标签范围;values是设置图表数据范围,line为设置图表线条属性,包括颜色宽度等.

set_x_axis(options):设置图表X轴选项,例如:

chart.set_x_axis({
'name':'EARNING per quarter',
'name_font':{'size':14,'bold':True},
'num_font':{'italic':True}
})
Copy after login

set_size(options):设置图表的大小,如

chart.set_size({'width':720,'height':576})

set_title(options):设置标题,如chart.set_title({'name':'TEST TITLE'}

set_style(style_id):设置图表样式,

set_table(options):设置x轴为数据表格式

下面是一个创建文件系统使用率的实例:

#coding:utf-8
 
import xlsxwriter
 
workbook = xlsxwriter.Workbook('d:\\suq\\test\\demo1.xlsx') #创建一个excel文件
worksheet = workbook.add_worksheet('sheet1') #在文件中创建一个sheet
#border:边框,align:对齐方式,bg_color:背景颜色,font_size:字体大小,bold:字体加粗 
top=workbook.add_format({'border':6,'align':'center','bg_color':'cccccc','font_size':13,'bold':True}) #设置单元格格式
title=[u'文件系统',u'总容量',u'使用大小',u'剩余大小'] #设置第一行标题信息
buname=['/dev/mapper/vg_basic-lv_root','tmpfs','/dev/sda1'] #设置左边第一排信息
 
worksheet.write_row('A1',title,top)
worksheet.write_column('A2',buname,top)
worksheet.set_column('A:D',40) #A到D列设置宽度,宽度设置必须是整列设置,高度必须是整行设置
#worksheet.set_row(0,40) #设置第一行高度为40像素
format_data=workbook.add_format({'align':'center','font_size':13}) #设置单元格格式
 
data=[[17678,4393,12388],[9768,8900,868],[24285,2715,21000]] #模拟文件系统的数据,data[0],[1],[2]分别表示全部空间,使用空间,剩余空间
worksheet.write_row('B2',data[0],format_data) #将数据写入,这里安装整行写入
worksheet.write_row('B3',data[1],format_data)
worksheet.write_row('B4',data[2],format_data)
 
chart=workbook.add_chart({'type':'column'}) #创建表格,表格类型为column
chart.set_title({'name':u'文件系统使用率'}) #设置表格的title
for i in ['B','C','D']:
chart.add_series({
'categories': 'sheet1!$A$2:$A$4',
'values':'sheet1!$'+i+'$2:$'+i+'$4',
'name':'=sheet1!$'+i+'$1'
})
#注意上面的表格中,每一行的数据在图中会显示在一起,也就是说values为B2:B4
 
chart.set_size({'width':800,'height':500}) #设置表格的大小
chart.set_y_axis({'name': 'MB'}) #设置表格y轴信息
#chart.set_style(33) #设置表格的样式
worksheet.insert_chart('A8',chart) #插入表格
workbook.close()
Copy after login

显示的图片结果如下:

相关推荐:

使用python实现XlsxWriter创建Excel文件并编辑

使用python3+xlrd解析Excel的实例

The above is the detailed content of python XlsxWriter module creates aexcel table. 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)

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 programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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.

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.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

See all articles