前言
我们经常使用Python来读写Excel文件,该怎么做呢,本篇文章为大家介绍一下如何使用Python进行Excel文件的读写。
引入Excel读写包
安装xlrd和xlwt包
1 2
| $ pip install xlrd $ pip install xlwt
|
然后在Python程序中引用这两个包
1 2 3 4
| import xlrd
import xlwt
|
读Excel文件
Excel文件如图所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| def read_excel(path): workbook = xlrd.open_workbook(path) sheet = workbook.sheet_by_index(0) row_count = sheet.nrows for i in range(0,row_count): rows = sheet.row_values(i) for j in range(0,len(rows)): if j != len(rows)-1: print(rows[j],end="") print(" ",end="") else: print(rows[j])
read_excel("E:\\example.xlsx")
|
读Excel的结果为:
1 2 3
| 姓名 年龄 工作 张函仑 25.0 程序员 李四 29.0 教师
|
写Excel文件
xlwt模块只支持书写xls文件
1 2 3 4 5 6 7 8 9
| def write_excel(path): workbook = xlwt.Workbook(encoding='utf-8') sheet1 = workbook.add_sheet('sheet1', cell_overwrite_ok=True) sheet1.write(3,0,"张三") sheet1.write(3,1,22) sheet1.write(3,2,"运营") workbook.save(path)
|
运行后的结果如下图所示
对于xlsx文件可以用xlsxwriter包来实现,具体代码如下
1 2 3 4 5 6 7 8 9 10
| import xlsxwriter def write_excel_xlsxwriter(path): workbook = xlsxwriter.Workbook("E:\\example.xlsx") worksheet = workbook.add_worksheet('sheet1') worksheet.write(3,0,"张三") worksheet.write(3, 1, 22) worksheet.write(3, 2, "运营") workbook.close()
|