一春畔、讀取excel表格的數(shù)據(jù)——xlrd
1.1?安裝
可使用pycharm搜索xlrd安裝褐缠,也可在virtualenv中執(zhí)行以下操作: pip install xlrd
1.2?使用方法
import xlrd
#讀取目標(biāo)excel表
xlsx = xlrd.open_workbook('d:/7月下旬入庫表.xlsx')
#讀取excel表中第一個(gè)工作簿
table = xlsx.sheet_by_index(0)
#讀取第一行政鼠,第一列的數(shù)據(jù)
print(table.cell_value(0, 0))
# 獲取所有sheet名字:xlsx.sheet_names()
# 獲取sheet數(shù)量:xlsx.nsheets
二、將數(shù)據(jù)寫入excel表——xlwt
2.1?安裝
可使用pycharm搜索xlwt安裝队魏,也可在virtualenv中執(zhí)行以下操作: pip install xlwt
2.2?使用方法
import xlwt
#創(chuàng)建一個(gè)excel表對(duì)象
new_workbook = xlwt.Workbook()
#在excel表中創(chuàng)建一個(gè)新的工作簿
worksheet = new_workbook.add_sheet('new_test')
#在工作簿中的第一行第一列寫入內(nèi)容
worksheet.write(0, 0, 'test')
#將excel表保存到本地
new_workbook.save('d:/test.xls')
三公般、實(shí)戰(zhàn)案例一
3.1?需求:逐行讀取舊表的內(nèi)容万搔,將其寫入到新表中
3.2?代碼實(shí)現(xiàn):
import xlrd,xlsxwriter
#讀取舊表
xlsx = xlrd.open_workbook('d:/7月下旬入庫表.xlsx')
#創(chuàng)建新表
new_workbook = xlsxwriter.Workbook('d:/test.xlsx')
#創(chuàng)建新工作簿
worksheet = new_workbook.add_worksheet()
#讀取舊表的第一個(gè)工作簿
table = xlsx.sheet_by_index(0)
#遍歷,將讀取到的數(shù)據(jù)寫入到新表
for i in range(0,table.nrows):
????for j in range(0,table.ncols):
????????worksheet.write(i, j, table.cell_value(i, j))
new_workbook.close()
四官帘、工具類xlutils和寫入數(shù)據(jù)的樣式
4.1?復(fù)制模板
from xlutils.copy import copy
tem_excel = xlrd.open_workbook('D:/日統(tǒng)計(jì).xls', formatting_info=True)
tem_sheet = tem_excel.sheet_by_index(0)
#將舊表的樣式復(fù)制到新表中
new_excel = copy(tem_excel)
new_sheet = new_excel.get_sheet(0)
4.2?設(shè)置寫入數(shù)據(jù)的樣式
style = xlwt.XFStyle()
#設(shè)置字體
font = xlwt.Font()
font.name = '微軟雅黑'
font.bold = True
font.height = 360
style.font = font
#設(shè)置邊框?yàn)榧?xì)邊框
borders = xlwt.Borders()
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
style.borders = borders
#設(shè)置對(duì)齊格式為居中對(duì)齊
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
style.alignment = alignment
#以指定的格式寫入數(shù)據(jù)
new_sheet.write(2, 1, 12, style)
new_sheet.write(3, 1, 18, style)
new_sheet.write(4, 1, 19, style)
new_sheet.write(5, 1, 15, style)
#保存
new_excel.save('D:/填寫.xls')