python处理Excel⽂件的⼏个模块在python中简单地处理excel⽂件,有⼏个相关的模块,各有千秋,本⽂将不定时收录。
收集了关于python处理excel⽂件的各种信息。
【注意】使⽤python处理excel⽂件前,请多备份⽂件,以防数据丢失。
------------------
0x01 xlrd
xlrd is a library for reading data and formatting information from Excel files, whether they are .xls or .xlsx files.安装:
pip install xlrd
使⽤:
只能读.xls、.xlsx⽂件(xlrd0.8.0+版本⽀持读取xlsx⽂件)
import xlrd
book = xlrd.open_workbook("pcat.xls")
print("The number of worksheets is {0}".format(book.nsheets))
print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
print("Cell B3 is {0}".ll_value(rowx=2, colx=1)))
for rx in ws):
w(rx))
0x02 xlwt
xlwt is a library for writing data and formatting information to older Excel files (ie: .xls)
pip install xlwt
使⽤:
⽤xlwt创建⼀个简单的.xls⽂件
import xlwt
from datetime import datetime
style0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on',
num_format_str='#,##0.00')
style1 = xlwt.easyxf(num_format_str='YYYY-MM-DD HH:MM:SS')
wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
ws.write(0, 0, 1234.56, style0)
ws.write(1, 0, w(), style1)
ws.write(2, 0, 1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))
wb.save('example.xls')
0x03 xlutils
安装:
(如果没安装xlrd、xlwt,会⾃动安装这2个模块)
pip install xlutils
使⽤:
import xlrd
import xlwt
import xlutils
py as copy
rdbook = xlrd.open_workbook('first.xls')
wtbook = py(rdbook)
wtsheet = _sheet(0)
type(wtsheet)
wtsheet.write(0,0,'')
wtbook.save('second.xls')
0x04 openpyxl
pip install openpyxl
使⽤:
写xlsx⽂件
from openpyxl import Workbook
wb = Workbook()
# grab the active worksheet
ws = wb.active
# Data can be assigned directly to cells
ws['A1'] = 42
# Rows can also be appended
ws.append([1, 2, 3])
# Python types will automatically be converted import datetime
ws['A2'] = w()
# Save the file
wb.save("sample.xlsx")
读xlsx⽂件
from openpyxl import load_workbook
wb = load_workbook(filename='pcat.xlsx')
sheet_ranges = wb['Sheet1']
print(sheet_ranges['A2'].value)
注意:
openpyxl不⽀持.xls格式。
读写⽂件前记得多备注,有时候可能有bug。
0x05 XlsxWriter
pip install xlsxwriter
python怎么读取xls文件使⽤:
import xlsxwriter
workbook = xlsxwriter.Workbook('hello_world.xlsx') worksheet = workbook.add_worksheet() worksheet.write('A1', 'Hello world')
workbook.close()
注意:
XlsxWriter不⽀持.xls格式。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论