之前給大家介紹過python高手之路python處理excel文件(方法匯總) Python操作Excel之xlsx文件 今天繼續圍繞python xlsx格式文件的操作方法給大家介紹,具體內容如下:
一.準備工作
二 .xlrd庫讀取
首先安裝xlrd庫,安裝方法:pip install xlrd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import xlrd #打開excel wb = xlrd.open_workbook( 'test_user_data.xlsx' ) #按工作簿定位工作表 sh = wb.sheet_by_name( 'testuserlogin' ) print (sh.nrows) #有效數據行數 print (sh.ncols) #有效數據列數 print (sh.cell( 0 , 0 ).value) #輸出第一行第一列的值 print (sh.row_values( 0 )) #輸出第一行的所有值 #將數據和標題組合成字典 print ( dict ( zip (sh.row_values( 0 ),sh.row_values( 1 )))) #遍歷excel,打印所有數據 for i in range (sh.nrows): print (sh.row_values(i)) |
輸出結果:
三.pandas庫讀取
1.安裝pandas: pip install pandas
2.代碼如下
1
2
3
4
5
|
import pandas as pd df = pd.read_excel( 'test_user_data.xlsx' ) data = df.values print ( "獲取到所有的值:\n{}" . format (data)) |
結果如下:
3.操作行列
讀取列數
1
2
3
4
5
|
import pandas as pd #讀取第一列、第二列、第四列 df = pd.read_excel( 'test_user_data.xlsx' ,sheet_name = 'testuserlogin' ,usecols = [ 0 , 1 , 3 ]) data = df.values print (data) |
讀取行數
1
2
3
4
5
|
import pandas as pd #讀取第一行 df = pd.read_excel( 'test_user_data.xlsx' ,sheet_name = 'testuserlogin' ,nrows = 1 ) data = df.values print (data) |
以上就是python操作xlsx格式文件并讀取的詳細內容,更多關于python xlsx格式文件的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/chenchen5152/article/details/117389616