处理excel
读取excel——xlrd模块
函数 | 说明 |
---|
xlrd.open_workbook | 打开excel,返回xlrd.book.Book格式数据 |
xlrd.xldate_as_datetime(cell.value,0) | 数值型时间转化为时间对象 |
xlrd.xldate_as_tuple(cell.value, 0) | 数值型时间转化为元祖对象 |
xlrd.book.Book数据属性
函数 | 说明 |
---|
.nsheets | 返回表数量 |
.sheets() | 返回所有表,生成一个列表 |
.sheet_names() | 返回所有表名称 |
.sheet_by_name() | 根据名称获取表(sheet格式数据) |
.sheet_by_index() | 根据索引获取表 |
sheet格式数据属性
函数 | 说明 |
---|
.name | 返回单个表名称 |
.nrows | 表中行数 |
.ncols | 表中列数 |
.row() | 根据索引返回列 |
.col() | 根据索引返回行 |
.row_values() | 根据索引返回行值 |
.col_values() | 根据索引返回列值 |
.cell(行索引,列索引) | 获取单元格(Cell格式) |
.cell_value(行索引,列索引) | 单元格数值 |
.cell_ctype(行索引,列索引) | 单元格数值类型 |
Cell格式数据属性
函数 | 说明 |
---|
Cell.value | 单元格数值 |
Cell.ctype | 单元格数值的类型 |
单元格数值类型
Type symbol | ctype值 | Python类型 |
---|
XL_CELL_EMPTY | 0 | 空字符串 |
XL_CELL_TEXT | 1 | 字符串 |
XL_CELL_NUMBER | 2 | float |
XL_CELL_DATE | 3 | float |
XL_CELL_BOOLEAN | 4 | int; 1表示True, 0表示False |
XL_CELL_ERROR | 5 | 错误 |
XL_CELL_BLANK | 6 | 空 |
写入excel——xlwt模块
函数 | 说明 |
---|
xlwt.Workbook() | 创建excel,返回xlwt.Workbook.Workbook格式数据 |
xlwt.Workbook.Workbook格式数据属性
函数 | 说明 |
---|
.add_sheet(表名,cell_overwrite_ok=True) | 添加表并命名,Worksheet格式 |
wd.save(’./data_files/test_write.xls’) | 保存文件并命名 |
Worksheet格式数据属性
函数 | 说明 |
---|
.write(行索引,列索引,值) | 写入单元格值 |
.row() | 行,Row格式 |
.col() | 列,Column l格式 |
处理word——docx
pip install python-docx
函数 | 说明 |
---|
from docx import Document | 导入Document包 |
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT | 导入包,文档设置的常量 |
from docx.shared import Mm,RGBColor | 导入包,文档设置单位和颜色,此处导入毫米 |
Document() | 创建文档,Document格式 |
Document格式数据属性
函数 | 说明 |
---|
.add_heading(标题,n) | 添加标题,n代表标题级别,Paragraph格式 |
.add_paragraph(内容) | 添加段落 |
.add_paragraph(内容,style=‘List Number’) | 添加有序列表 |
.add_paragraph(内容,style='List Bullet) | 添加无序列表 |
.add_table(rows=1,cols=3) | 添加表格 |
.add_picture(地址,width=Mm(5)) | 添加图片 |
.add_page_break() | 添加分页符 |
.save() | 保存文档并命名 |
Paragraph格式数据属性
函数 | 说明 |
---|
.paragraph_format.alignment | 段落格式-对齐 |
.paragraph_format.left_indent | 缩进 |
.add_run().bold=True | 追加段落内容,加粗字体 |
.font.name | 设置字体样式 |
.font.size | 设置字体大小 |
.font.color.rgb = RGBColor(0,0,0,) | 设置字体颜色 |
.italic=True | 设置斜体 |
.underline=True | 下划线 |
WD_PARAGRAPH_ALIGNMENT 常量
常量 | 说明 |
---|
CENTER | 居中 |
LEFT | 靠左 |
RIGHT | 靠右 |