python处理excel数据的方法:1、使用xlrd来处理;2、使用【xlutils+xlrd】来处理;3、使用xlwt来处理;4、使用pyExcelerator来处理;5、使用Pandas库来处理。
这里有一张excel数据表,下面我们通过示例来看看xlrd、xlwt、xluntils、pyExcelerator和Pandas是如何处理excel文件数据的。【视频教程推荐:python教程】
python处理excel数据的方法:
方法一:使用xlrd来处理excel数据
示例1:python读取excel文件特定数据
import xlrd data = xlrd.open_workbook('test.xls') # 打开xls文件 table = data.sheets()[0] # 打开第一张表 nrows = table.nrows # 获取表的行数 # 循环逐行输出 for i in range(nrows): if i == 0: # 跳过第一行 continue print table.row_values(i)[:13] # 取前十三列数据
示例2:python读取excel文件所有数据
import xlrd #打开一个xls文件 workbook = xlrd.open_workbook('test.xls') #抓取所有sheet页的名称 worksheets = workbook.sheet_names() print('worksheets is %s' %worksheets) #定位到sheet1 worksheet1 = workbook.sheet_by_name(u'Sheet1') """ #通过索引顺序获取 worksheet1 = workbook.sheets()[0] #或 worksheet1 = workbook.sheet_by_index(0) """ """ #遍历所有sheet对象 for worksheet_name in worksheets: worksheet = workbook.sheet_by_name(worksheet_name) """ #遍历sheet1中所有行row num_rows = worksheet1.nrows for curr_row in range(num_rows): row = worksheet1.row_values(curr_row) print('row%s is %s' %(curr_row,row)) #遍历sheet1中所有列col num_cols = worksheet1.ncols for curr_col in range(num_cols): col = worksheet1.col_values(curr_col) print('col%s is %s' %(curr_col,col)) #遍历sheet1中所有单元格cell for rown in range(num_rows): for coln in range(num_cols): cell = worksheet1.cell_value(rown,coln) print cell
方法二:使用xlutils+xlrd来处理excel数据
示例:向excel文件中写入数据
import xlrd import xlutils.copy #打开一个xls文件 rb = xlrd.open_workbook('test.xls') wb = xlutils.copy.copy(rb) #获取sheet对象,通过sheet_by_index()获取的sheet对象没有write()方法 ws = wb.get_sheet(0) #写入数据 ws.write(1, 1, 'changed!') #添加sheet页 wb.add_sheet('sheetnnn2',cell_overwrite_ok=True) #利用保存时同名覆盖达到修改excel文件的目的,注意未被修改的内容保持不变 wb.save('test.xls')
方法三:使用xlwt来处理excel数据
示例1:新建excel文件并写入数据
import xlwt #创建workbook和sheet对象 workbook = xlwt.Workbook() #注意Workbook的开头W要大写 sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True) sheet2 = workbook.add_sheet('sheet2',cell_overwrite_ok=True) #向sheet页中写入数据 sheet1.write(0,0,'this should overwrite1') sheet1.write(0,1,'aaaaaaaaaaaa') sheet2.write(0,0,'this should overwrite2') sheet2.write(1,2,'bbbbbbbbbbbbb') #保存该excel文件,有同名文件时直接覆盖 workbook.save('test.xls') print '创建excel文件完成!'
方法四:使用pyExcelerator来处理excel数据
示例1:读excel文件中的数据
import pyExcelerator #parse_xls返回一个列表,每项都是一个sheet页的数据。 #每项是一个二元组(表名,单元格数据)。其中单元格数据为一个字典,键值就是单元格的索引(i,j)。如果某个单元格无数据,那么就不存在这个值 sheets = pyExcelerator.parse_xls('test.xls') print sheets
示例2:新建excel文件并写入数据
import pyExcelerator #创建workbook和sheet对象 wb = pyExcelerator.Workbook() ws = wb.add_sheet(u'第一页') #设置样式 myfont = pyExcelerator.Font() myfont.name = u'Times New Roman' myfont.bold = True mystyle = pyExcelerator.XFStyle() mystyle.font = myfont #写入数据,使用样式 ws.write(0,0,u'ni hao 帕索!',mystyle) #保存该excel文件,有同名文件时直接覆盖 wb.save('E:\\Code\\Python\\mini.xls') print '创建excel文件完成!'
方法五:使用Pandas库来处理excel数据
示例1:读取excel数据
#导入pandas模块 import pandas as pd #直接默认读取到这个Excel的第一个表单 sheet = pd.read_excel('test.xls') #默认读取前5行数据 data=sheet.head() print("获取到所有的值:\n{0}".format(data))#格式化输出 #也可以通过指定表单名来读取数据 sheet2=pd.read_excel('test.xlsx',sheet_name='userRegister') data2=sheet2.head()#默认读取前5行数据 print("获取到所有的值:\n{0}".format(data2))#格式化输出
示例2:操作Excel中的行列
#导入pandas模块 import pandas as pd sheet=pd.read_excel('webservice_testcase.xlsx')#这个会直接默认读取到这个Excel的第一个表单 #读取制定的某一行数据: data=sheet.ix[0].values #0表示第一行 这里读取数据并不包含表头 print("读取指定行的数据:\n{0}".format(data)) #读取指定的多行: data2=sheet.ix[[0,1]].values print("读取指定行的数据:\n{0}".format(data2)) #读取指定行列的数据: data3=sheet.ix[0,1]#读取第一行第二列的值 print("读取指定行的数据:\n{0}".format(data3)) #读取指定的多行多列的值: data4=sheet.ix[[1,2],['姓名','电话']].values #读取第二行第三行的姓名以及电话列的值,这里需要嵌套列表 print("读取指定行的数据:\n{0}".format(data4)) #读取所有行指定的列的值: data5=sheet.ix[:,['姓名','电话']].values #姓名以及电话列的值 print("读取指定行的数据:\n{0}".format(data5)) #获取行号输出: print("输出行号列表",sheet.index.values) #获取列名输出: print("输出列标题",sheet.columns.values)
以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注php中文网相关教程栏目!!!
The above is the detailed content of How python processes excel data. For more information, please follow other related articles on the PHP Chinese website!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
