python讀取xls
Ⅰ python怎麼讀取excel文件
最近由於經常要用到Excel,需要根據Excel表格中的內容對一些apk進行處理,手動處理很麻煩,於是決定寫腳本來處理。首先貼出網上找來的讀寫Excel的腳本。
1.讀取Excel(需要安裝xlrd):
#-*- coding: utf8 -*-
import xlrd
fname = "reflect.xls"
bk = xlrd.open_workbook(fname)
shxrange = range(bk.nsheets)
try:
sh = bk.sheet_by_name("Sheet1")
except:
print "no sheet in %s named Sheet1" % fname
#獲取行數
nrows = sh.nrows
#獲取列數
ncols = sh.ncols
print "nrows %d, ncols %d" % (nrows,ncols)
#獲取第一行第一列數據
cell_value = sh.cell_value(1,1)
#print cell_value
row_list = []
#獲取各行數據
for i in range(1,nrows):
row_data = sh.row_values(i)
row_list.append(row_data)
Ⅱ python怎麼讀取excel文件
1.讀取Excel(需要安裝xlrd):
#-*- coding: utf8 -*-import xlrdfname = "reflect.xls"bk = xlrd.open_workbook(fname)shxrange = range(bk.nsheets)try:sh = bk.sheet_by_name("Sheet1")except:print "no sheet in %s named Sheet1" % fname#獲取行數nrows = sh.nrows#獲取列數ncols = sh.ncolsprint "nrows %d, ncols %d" % (nrows,ncols)#獲取第一行第一列數據cell_value = sh.cell_value(1,1)#print cell_valuerow_list = []#獲取各行數據for i in range(1,nrows):row_data = sh.row_values(i)row_list.append(row_data)2.寫入Excel(需安裝pyExcelerator)
from pyExcelerator import *w = Workbook() #創建一個工作簿ws = w.add_sheet('Hey, Hades') #創建一個工作表ws.write(0,0,'bit') #在1行1列寫入bitws.write(0,1,'huang') #在1行2列寫入huangws.write(1,0,'xuan') #在2行1列寫入xuanw.save('mini.xls') #保存3.再舉個自己寫的讀寫Excel的例子
讀取reflect.xls中的某些信息進行處理後寫入mini.xls文件中。
4.現在我需要根據Excel文件中滿足特定要求的apk的md5值來從伺服器獲取相應的apk樣本,就需要這樣做:
#-*-coding:utf8-*-import xlrdimport osimport shutilfname = "./excelname.xls"bk = xlrd.open_workbook(fname)shxrange = range(bk.nsheets)try:#打開Sheet1工作表sh = bk.sheet_by_name("Sheet1")except:print "no sheet in %s named Sheet1" % fname#獲取行數nrows = sh.nrows#獲取列數ncols = sh.ncols#print "nrows %d, ncols %d" % (nrows,ncols)#獲取第一行第一列數據cell_value = sh.cell_value(1,1)#print cell_valuerow_list = []#range(起始行,結束行)for i in range(1,nrows):row_data = sh.row_values(i)if row_data[6] == "HXB":filename = row_data[3]+".apk"#print "%s %s %s" %(i,row_data[3],filename)filepath = r"./1/"+filenameprint "%s %s %s" %(i,row_data[3],filepath)if os.path.exists(filepath):shutil.(filepath, r"./myapk/")補充一個使用xlwt3進行Excel文件的寫操作。
import xlwt3if __name__ == '__main__':datas = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]#二維數組file_path = 'D:\test.xlsx'wb = xlwt3.Workbook()sheet = wb.add_sheet('test')#sheet的名稱為test#單元格的格式style = 'pattern: pattern solid, fore_colour yellow; '#背景顏色為黃色style += 'font: bold on; '#粗體字style += 'align: horz centre, vert center; '#居中header_style = xlwt3.easyxf(style)row_count = len(datas)col_count = len(datas[0])for row in range(0, row_count):col_count = len(datas[row])for col in range(0, col_count):if row == 0:#設置表頭單元格的格式sheet.write(row, col, datas[row][col], header_style)else:sheet.write(row, col, datas[row][col])wb.save(file_path)輸出的文件內容如下圖:
註:以上代碼在Python 3.x版本測試通過。
Ⅲ 如何用python讀取excel文件
1.首先說明我是使用的python3.5,我的office版本是2010,首先打開dos命令窗,安裝必須的兩個庫,命令是:
pip3 install xlrd
Pip3 install xlwt
2.准備好excel,例如我的一個工作文件,我放在D盤/網路經驗/11.xlsx,只有一個頁簽A,內容是一些銷售數據
3.打開pycharm,新建一個excel.py的文件,首先導入支持庫
import xlrdimport xlwt
4.針對剛入門的新手,先介紹三個知識,第一個:獲取excel的sheet名稱,第二:獲取excel行數與列數,第三:獲取第幾行第幾列的具體值,這是最常用的三個知識點
5.貼出代碼,具體分析:
(1)要操作excel,首先得打開excel,使用open_workbook(‘路徑’)
(2)要獲取行與列,使用nrows(行),ncols(列)
(3)獲取具體的值,使用cell(row,col).value
workbook=xlrd.open_workbook(r'E:11.xlsx')print (workbook.sheet_names()) sheet2=workbook.sheet_by_name('A') nrows=sheet2.nrows ncols=sheet2.ncols print(nrows,ncols) cell_A=sheet2.cell(1,1).value print(cell_A)
6.要在excel里寫入值,就要使用write屬性,重點說明寫入是用到xlwt這個支援庫,思路是先新建excel,然後新建頁簽B,然後將一組數據寫入到B,最後保存為excel.xls,這里建議保存為2003的格式,大部分電腦都能打開,特別注意保存的excel的路徑是在python工作文件的目錄下面,貼出代碼:
stus = [['年', '月'], ['2018', '10'], ['2017', '9'], ['2016', '8']]Excel = xlwt.Workbook() # 新建excelsheet = Excel.add_sheet('B') #新建頁簽Brow = 0for stu in stus: col = 0 for s in stu: sheet.write(row, col, s) #開始寫入 col = col + 1 row = row + 1Excel.save('Excel.xls') #保存
關於如何用python讀取excel文件,環球青藤小編就和大家分享到這里了,學習是永無止境的,學習一項技能更是受益終身,所以,只要肯努力學,什麼時候開始都不晚。如果您還想繼續了解關於python編程的學習方法及素材等內容,可以點擊本站其他文章學習。
Ⅳ python讀取excel格式
Python讀寫EXCEL文件常用方法大全
Huny 信息網路工程研究中心 2020-12-19
1 前言
python讀寫excel的方式有很多,不同的模塊在讀寫的講法上稍有區別,這里我主要介紹幾個常用的方式。
用xlrd和xlwt進行excel讀寫;
用openpyxl進行excel讀寫;
用pandas進行excel讀寫;
參考:
https://www.python-excel.org/
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html#pandas.read_excel
https://www.jianshu.com/p/19219542bf23
2 數據准備
為了方便演示,我這里新建了一個data.xls和data.xlsx文件,第一個工作表sheet1區域「A1:E5」的內容如下,用於測試讀寫excel的代碼:
3 xlrd和xlwt
xlrd是一個庫,用於從Excel文件中以.xls格式讀取數據和格式化信息
xlwt是一個庫,用於將數據和格式化信息寫入較舊的Excel文件(例如:.xls)。
示例
pip install xlrd
pip install xlwt
我們開始來讀取文件的內容
import xlrd
import os
file_path = os.path.dirname(os.path.abspath(__file__))
base_path = os.path.join(file_path, 'data.xlsx')
book = xlrd.open_workbook(base_path)
sheet1 = book.sheets()[0]
nrows = sheet1.nrows
print('表格總行數', nrows)
ncols = sheet1.ncols
print('表格總列數', ncols)
row3_values = sheet1.row_values(2)
print('第3行值', row3_values)
col3_values = sheet1.col_values(2)
print('第3列值', col3_values)
cell_3_3
Ⅳ python 如何讀取 excel 指定單元格內容
1、首先打開電腦上編寫python的軟體。
Ⅵ 怎麼用python讀取excel表格的數據
一、讀excel表
讀excel要用到xlrd模塊,官網安裝(http://pypi.python.org/pypi/xlrd)。然後就可以跟著裡面的例子稍微試一下就知道怎麼用了。大概的流程是這樣的:
1、導入模塊
復制代碼代碼如下:
import xlrd
2、打開Excel文件讀取數據
復制代碼代碼如下:
data = xlrd.open_workbook('excel.xls')
3、獲取一個工作表
① table = data.sheets()[0] #通過索引順序獲取
② table = data.sheet_by_index(0) #通過索引順序獲取
③ table = data.sheet_by_name(u'Sheet1')#通過名稱獲取
4、獲取整行和整列的值(返回數組)
復制代碼代碼如下:
table.row_values(i)
table.col_values(i)
5、獲取行數和列數
復制代碼代碼如下:
table.nrows
table.ncols
6、獲取單元格
復制代碼代碼如下:
table.cell(0,0).value
table.cell(2,3).value
就我自己使用的時候覺得還是獲取cell最有用,這就相當於是給了你一個二維數組,餘下你就可以想怎麼干就怎麼幹了。得益於這個十分好用的庫代碼很是簡潔。但是還是有若干坑的存在導致話了一定時間探索。現在列出來供後人參考吧:
1、首先就是我的統計是根據姓名統計各個表中的信息的,但是調試發現不同的表中各個名字貌似不能夠匹配,開始懷疑過編碼問題,不過後來發現是因為空格。因為在excel中輸入的時候很可能會順手在一些名字後面加上幾個空格或是tab鍵,這樣看起來沒什麼差別,但是程序處理的時候這就是兩個完全不同的串了。我的解決方法是給每個獲取的字元串都加上strip()處理一下。效果良好
2、還是字元串的匹配,在判斷某個單元格中的字元串(中文)是否等於我所給出的的時候發現無法匹配,並且各種unicode也不太奏效,網路過一些解決方案,但是都比較復雜或是沒用。最後我採用了一個比較變通的方式:直接從excel中獲取我想要的值再進行比較,效果是不錯就是通用行不太好,個呢不能問題還沒解決。
二、寫excel表
寫excel表要用到xlwt模塊,官網下載(http://pypi.python.org/pypi/xlwt)。大致使用流程如下:
1、導入模塊
復制代碼代碼如下:
import xlwt
2、創建workbook(其實就是excel,後來保存一下就行)
復制代碼代碼如下:
workbook = xlwt.Workbook(encoding = 'ascii')
3、創建表
復制代碼代碼如下:
worksheet = workbook.add_sheet('My Worksheet')
4、往單元格內寫入內容
復制代碼代碼如下:
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
5、保存
復制代碼代碼如下:
workbook.save('Excel_Workbook.xls')
由於我的需求比較簡單,所以這上面沒遇到什麼問題,唯一的就是建議還是用ascii編碼,不然可能會有一些詭異的現象。
當然xlwt功能遠遠不止這些,他甚至可以設置各種樣式之類的。附上一點例子
復制代碼代碼如下:
Examples Generating Excel Documents Using Python's xlwt
Here are some simple examples using Python's xlwt library to dynamically generate Excel documents.
Please note a useful alternative may be ezodf, which allows you to generate ODS (Open Document Spreadsheet) files for LibreOffice / OpenOffice. You can check them out at:http://packages.python.org/ezodf/index.html
The Simplest Example
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('My Worksheet')
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
workbook.save('Excel_Workbook.xls')
Formatting the Contents of a Cell
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('My Worksheet')
font = xlwt.Font() # Create the Font
font.name = 'Times New Roman'
font.bold = True
font.underline = True
font.italic = True
style = xlwt.XFStyle() # Create the Style
style.font = font # Apply the Font to the Style
worksheet.write(0, 0, label = 'Unformatted value')
worksheet.write(1, 0, label = 'Formatted value', style) # Apply the Style to the Cell
workbook.save('Excel_Workbook.xls')
Attributes of the Font Object
font.bold = True # May be: True, False
font.italic = True # May be: True, False
font.struck_out = True # May be: True, False
font.underline = xlwt.Font.UNDERLINE_SINGLE # May be: UNDERLINE_NONE, UNDERLINE_SINGLE, UNDERLINE_SINGLE_ACC, UNDERLINE_DOUBLE, UNDERLINE_DOUBLE_ACC
font.escapement = xlwt.Font.ESCAPEMENT_SUPERSCRIPT # May be: ESCAPEMENT_NONE, ESCAPEMENT_SUPERSCRIPT, ESCAPEMENT_SUBSCRIPT
font.family = xlwt.Font.FAMILY_ROMAN # May be: FAMILY_NONE, FAMILY_ROMAN, FAMILY_SWISS, FAMILY_MODERN, FAMILY_SCRIPT, FAMILY_DECORATIVE
font.charset = xlwt.Font.CHARSET_ANSI_LATIN # May be: CHARSET_ANSI_LATIN, CHARSET_SYS_DEFAULT, CHARSET_SYMBOL, CHARSET_APPLE_ROMAN, CHARSET_ANSI_JAP_SHIFT_JIS, CHARSET_ANSI_KOR_HANGUL, CHARSET_ANSI_KOR_JOHAB, CHARSET_ANSI_CHINESE_GBK, CHARSET_ANSI_CHINESE_BIG5, CHARSET_ANSI_GREEK, CHARSET_ANSI_TURKISH, CHARSET_ANSI_VIETNAMESE, CHARSET_ANSI_HEBREW, CHARSET_ANSI_ARABIC, CHARSET_ANSI_BALTIC, CHARSET_ANSI_CYRILLIC, CHARSET_ANSI_THAI, CHARSET_ANSI_LATIN_II, CHARSET_OEM_LATIN_I
font.colour_index = ?
font.get_biff_record = ?
font.height = 0x00C8 # C8 in Hex (in decimal) = 10 points in height.
font.name = ?
font.outline = ?
font.shadow = ?
Setting the Width of a Cell
import xltw
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, 'My Cell Contents')
worksheet.col(0).width = 3333 # 3333 = 1" (one inch).
workbook.save('Excel_Workbook.xls')
Entering a Date into a Cell
import xlwt
import datetime
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
style = xlwt.XFStyle()
style.num_format_str = 'M/D/YY' # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
worksheet.write(0, 0, datetime.datetime.now(), style)
workbook.save('Excel_Workbook.xls')
Adding a Formula to a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, 5) # Outputs 5
worksheet.write(0, 1, 2) # Outputs 2
worksheet.write(1, 0, xlwt.Formula('A1*B1')) # Should output "10" (A1[5] * A2[2])
worksheet.write(1, 1, xlwt.Formula('SUM(A1,B1)')) # Should output "7" (A1[5] + A2[2])
workbook.save('Excel_Workbook.xls')
Adding a Hyperlink to a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, xlwt.Formula('HYPERLINK("http://www.google.com";"Google")')) # Outputs the text "Google" linking to http://www.google.com
workbook.save('Excel_Workbook.xls')
Merging Columns and Rows
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write_merge(0, 0, 0, 3, 'First Merge') # Merges row 0's columns 0 through 3.
font = xlwt.Font() # Create Font
font.bold = True # Set font to Bold
style = xlwt.XFStyle() # Create Style
style.font = font # Add Bold Font to Style
worksheet.write_merge(1, 2, 0, 3, 'Second Merge', style) # Merges row 1 through 2's columns 0 through 3.
workbook.save('Excel_Workbook.xls')
Setting the Alignment for the Contents of a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
alignment = xlwt.Alignment() # Create Alignment
alignment.horz = xlwt.Alignment.HORZ_CENTER # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
alignment.vert = xlwt.Alignment.VERT_CENTER # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
style = xlwt.XFStyle() # Create Style
style.alignment = alignment # Add Alignment to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')
Adding Borders to a Cell
# Please note: While I was able to find these constants within the source code, on my system (using LibreOffice,) I was only presented with a solid line, varying from thin to thick; no dotted or dashed lines.
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
borders = xlwt.Borders() # Create Borders
borders.left = xlwt.Borders.DASHED # May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED, THIN_DASH_DOTTED, MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED, SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D.
borders.right = xlwt.Borders.DASHED
borders.top = xlwt.Borders.DASHED
borders.bottom = xlwt.Borders.DASHED
borders.left_colour = 0x40
borders.right_colour = 0x40
borders.top_colour = 0x40
borders.bottom_colour = 0x40
style = xlwt.XFStyle() # Create Style
style.borders = borders # Add Borders to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')
Setting the Background Color of a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
pattern = xlwt.Pattern() # Create the Pattern
pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12
pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on...
style = xlwt.XFStyle() # Create the Pattern
style.pattern = pattern # Add Pattern to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')
TODO: Things Left to Document
- Panes -- separate views which are always in view
- Border Colors (documented above, but not taking effect as it should)
- Border Widths (document above, but not working as expected)
- Protection
- Row Styles
- Zoom / Manification
- WS Props?
Source Code for reference available at: https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/
Ⅶ 怎樣用python,讀取excel中的一列數據
用python讀取excel中的一列數據步驟如下:
1、首先打開dos命令窗,安裝必須的兩個庫,命令是:pip3 installxlrd;Pip3 install xlwt。
Ⅷ python中讀取excel文件
常用的簡單的用法:
from xlrd import open_workbook
book=open_workbook(r'C:\Users\admin\Desktop\q.xlsx')
sheet=book.sheets_names()[0]#第一個工作表名稱
sheet=data.sheet_by_name('Sheet1')#獲得第一個工作表
sheet=book.sheets()[0]#獲得第一個工作表
#獲取總行數
nrows = table.nrows
#獲取總列數
ncols = table.ncols
#工作表的數目
book.nsheets
sheet.cell(0,1)
sheet.row(0)
#讀取第二列的內容,從第二行開始,並對其求和
sum(x.value for x in sheet.col(1,start_rowx=1))
sum(sheet.col_values(1,start_rowx=1))#同上
Ⅸ python 讀寫一個xls文件
一、讀取excel
這里介紹一個不錯的包xlrs,可以工作在任何平台。這也就意味著你可以在Linux下讀取Excel文件。
首先,打開workbook;
代碼如下:
import xlrd
wb = xlrd.open_workbook('myworkbook.xls')
檢查表單名字:
代碼如下:
wb.sheet_names()
得到第一張表單,兩種方式:索引和名字
代碼如下:
sh = wb.sheet_by_index(0)
sh = wb.sheet_by_name(u'Sheet1')
遞歸列印出每行的信息:
代碼如下:
for rownum in range(sh.nrows):
print sh.row_values(rownum)
如果只想返回第一列數據:
代碼如下:
first_column = sh.col_values(0)
通過索引讀取數據:
cell_A1 = sh.cell(0,0).value
cell_C4 = sh.cell(rowx=3,colx=2).value
注意:這里的索引都是從0開始的。
二、寫excel
這里介紹一個不錯的包xlwt,可以工作在任何平台。這也就意味著你可以在Linux下保存Excel文件。
基本部分
在寫入Excel表格之前,你必須初始化workbook對象,然後添加一個workbook對象。比如:
代碼如下:
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')
這樣表單就被創建了,寫入數據也很簡單:
代碼如下:
# indexing is zero based, row then column
sheet.write(0,1,'test text')
之後,就可以保存文件(這里不需要想打開文件一樣需要close文件):
代碼如下:
wbk.save('test.xls')