当前位置:首页 » 编程语言 » python读取表格数据

python读取表格数据

发布时间: 2023-03-12 03:00:21

A. python中的pandas如何读取excel中指定单元格的值

pandas 读取指定单元格 第2行,第3列
import pandas as pd
df = pd.read_excel('测试.xlsx')
cell = df.iat[0, 2]
[0, 2] 表示单元格的行列 pandas 默认跳过表头从第二行开始 第三列是2 (012)

B. 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

C. 使用python读取excel中的数据,并重新写入到新的excel中

使用Python3运行
起初是读取excel中的数据,进行相关的计算将结果追加在后面,没有找到合适的办法,就只能采用这种读取数据,进行相关操作,重新写入的方法

(1)使用xlrd打开xls文件,读取数据
(2)将需要的数据放进list中,进行相应的计算得出结果
(3)使用xlutils的将xlrd对象转化为xlwt对象
(4)使用转化的xlwt对象的write方法,将结果写入
(5)使用xlwt的save进行保存

主要用它读取Excel数据

主要用它来将数据写入到excel中

主要用xlutils的方法将xlrd对象转化为xlwt对象,好来进行写入

删除了一些东西大致如下

D. python怎么读取excel的数据

最近由于经常要用到Excel,需要根据Excel表格中的内容对一些apk进行处理,手动处理很麻烦,于是决定写脚本来处理。首先贴出网上找来的读写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)

12345678from 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文件中。

#-*- coding: utf8 -*-import xlrdfrom pyExcelerator import *w = Workbook()ws = w.add_sheet('Sheet1')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" % fnamenrows = sh.nrowsncols = sh.ncolsprint "nrows %d, ncols %d" % (nrows,ncols)cell_value = sh.cell_value(1,1)#print cell_valuerow_list = []mydata = []for i in range(1,nrows):row_data = sh.row_values(i)pkgdatas = row_data[3].split(',')#pkgdatas.split(',')#获取每个包的前两个字段for pkgdata in pkgdatas:pkgdata = '.'.join((pkgdata.split('.'))[:2])mydata.append(pkgdata)#将列表排序mydata = list(set(mydata))print mydata#将列表转化为字符串mydata = ','.join(mydata)#写入数据到每行的第一列ws.write(i,0,mydata)mydata = []row_list.append(row_data[3])#print row_listw.save('mini.xls')

4.现在我需要根据Excel文件中满足特定要求的apk的md5值来从服务器获取相应的apk样本,就需要这样做:

252627282930313233#-*-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文件的写操作。

2526import 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就这么!些了,简单吧

E. 怎么用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/

热点内容
动态规划01背包算法 发布:2024-11-05 22:17:40 浏览:849
nasm编译器如何安装 发布:2024-11-05 22:01:13 浏览:181
登录密码在微信的哪里 发布:2024-11-05 22:00:29 浏览:739
c防止反编译工具 发布:2024-11-05 21:56:14 浏览:247
安卓虚拟机怎么用 发布:2024-11-05 21:52:48 浏览:344
php时间搜索 发布:2024-11-05 20:58:36 浏览:479
燕山大学编译原理期末考试题 发布:2024-11-05 20:13:54 浏览:528
华为电脑出现临时服务器 发布:2024-11-05 20:05:08 浏览:408
斗战神免费挖矿脚本 发布:2024-11-05 19:53:25 浏览:665
网吧服务器分别是什么 发布:2024-11-05 19:45:32 浏览:392