python读取Excel文件和写入Excel文件的方式
path=os.path.realpath(__file__) cwd=os.path.split(path)[0] open(cwd+os.path.sep+"usage_result.xls","wb").write(response.content)
上面是写入文件的简单的一个方式。
一,读取Excel文件的方式:
1、使用xlrd包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import xlrd # 通过open_workbook()方法打开工作簿 wb = xlrd.open_workbook(filename) # 通过sheet_by_name()或者sheet_by_index()方法打开工作表对象 sheet_1 = wb.sheet_by_name( 'sheet_1' ) # 或者sheet_1 = wb.sheet_by_index(0) # 通过ncols和nrows 分别获得工作表的列数和行数 sheet_1.ncols sheet_1.nrows # 通过cell().value方法获得单元格的数值 sheet_1.cell(0,0).value |
2、使用OpenPyxl包
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import openpyxl as oxl # 通过load_workbook()方法打开工作簿对象 wb = oxl.load_workbook(filename) # 通过get_active_sheet()方法打开工作表 ws = wb.get_active_sheet() # 像使用excel函数一样获取单元格的数值 cell = ws[ 'B4' ] ws[ 'B1' : 'B4' ] |
3、使用pandas包
1
2
3
4
5
|
import pandas as pd #通过read_excel()方法生成DataFrame对象 df = pd.read_excel(filename, 'sheet_1' ,header=None) |
然后可以使用DataFrame切片函数对df数据进行操作
以上就是“python怎么读取excel文件中的数据?(py
二。那么如果读取文件呢,比如 python如何读取一个excel文件内容呢:
一、Excel的写入方式:
1、使用xlwt包(注意只支持xls格式的文件)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import xlwt # 创建一个工作簿对象 wb = xlwt.Workbook() # 通过add_sheet()方法在工作簿对象中添加一个或者多个工作表 wb.add_sheet( 'sheet_1' , 'sheet_2' ,cell_overwrite_ok=True) # 通过get_sheet()方法打开需要编辑的工作表 ws = wb.get_sheet( 'sheet_1' ) # 通过write()方法将数据写入excel ws.write(0,0,100) # 表示将数字100写入第1行第一列单元格中 # 保存文件到磁盘 wb.save(fielname) |
2、使用xlsxwriter包(注意只支持xlsx格式的文件)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import xlsxwriter # 创建一个工作簿对象 wb = xlsxwriter.Workbook(filename) # 通过add_worksheet()方法在工作簿中添加一个或多个工作表 ws = wb.add_worksheet( 'sheet_1' ) # 通过write()方法将数据写入工作表 ws.write(0,0,100) # 关闭工作簿对象 wb.close() |
3、使用OpenPyxl包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import openpyxl as oxl # 创建一个工作簿对象 wb = oxl.Workbook() # 通过create_sheet()方法在工作簿中创建一个或多个工作表 ws = wb.create_sheet(index=0,title= 'sheet_1' ) # 通过cell().value方法将数据写入工作表 ws.cell(row=0,column=0).value = 100 # 保存文件到磁盘 wb.save(filename) |
4、使用pandas包
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import pandas as pd # 通过ExcelWriter()方法创建一个工作簿对象 wb = pd.ExcelWriter(filename) # 通过to_excel()方法将数据写入工作表 df.to_excel(wb, 'sheet_1' ) # 保存文件到磁盘 wb.save() |
参考:http://www.phpxs.com/post/9376/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)