最近写了个读写表格的工具,在这里记录一下相关技术。
首先明确一下常见表格的格式,最常见的是xls和xlsx,前者是Excel2003版本的默认保存格式,后者是Excel2007以后版本的默认保存格式。
Excel2007向下兼容xls格式,但Excel2003不能兼容xlsx格式。
因此考虑到兼容性,最好采用xls格式作为默认格式进行处理。
除此以外还有一种xlsm格式,是一种特殊的xlsx文件,只是包含了宏命令,在数据处理中比较少见。
xlsx读取
import xlrd wb = xlrd.open_workbook(filename="test.xlsx")#打开文件 print(wb.sheet_names())#获取所有表格名字 sheet1 = wb.sheet_by_index(0)#通过索引获取表格 sheet2 = wb.sheet_by_name('年级')#通过名字获取表格 print(sheet1.name,sheet1.nrows,sheet1.ncols) rows = sheet1.row_values(2)#获取行内容 cols = sheet1.col_values(3)#获取列内容 print(rows) print(cols) print(sheet1.cell(1,0).value)#获取表格里的内容,三种方式 print(sheet1.cell_value(1,0)) print(sheet1.row(1)[0].value)
xlsx写入
import xlwt f = xlwt.Workbook() sheet1 = f.add_sheet('学生',cell_overwrite_ok=True) row0 = ["姓名","年龄","出生日期","爱好"] colum0 = ["张三","李四","恋习Python","小明","小红","无名"] #写第一行 for i in range(0,len(row0)): sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True)) #写第一列 for i in range(0,len(colum0)): sheet1.write(i+1,0,colum0[i],set_style('Times New Roman',220,True)) sheet1.write(1,3,'2006/12/12') sheet1.write_merge(6,6,1,3,'未知')#合并行单元格 sheet1.write_merge(1,2,3,3,'打游戏')#合并列单元格 sheet1.write_merge(4,5,3,3,'打篮球') f.save('test.xls')
除了Excel以外,还有一种类表格csv格式,这是一种明文存储,以行和分隔符为界的数据存储格式, 第一行可以是列名 ,分隔符默认是逗号,也可以是分号或制表符。
许多程序特别是数据库都支持导入导出该格式,用来作为与其他软件进行数据交换的通用格式。
csv格式读写可以使用python自带的csv库,或者第三方的pandas库。
读csv
import csv with open('test.csv','r') as myFile: lines=csv.reader(myFile) for line in lines: print line
import pandas pandas.read_csv('test.csv',encoding='gbk') #其他常用参数 #sep=";" 指定逗号以外的分隔符 #delimiter=";" 备选分隔符,指定了这个则sep失效 #usecols=["name"] 读取部分列,可以指定列序号或者列名
写csv
import csv #由于默认写入一行后会留空一行会写入,因此newline=""的意思就是不留空行。 with open('frank.csv','w', newline='' ) as myFile: writer = csv.writer(myFile) writer.writerow(['frank', 'yangchao']) writer.writerows([('Bob','Tom'), ('liuwei', 'liuyong')])
import pandas Data = {'col2': [3, 4], 'col4': [1, 2]} DF = pd.DataFrame(Data) #可以避免dict的key无序性 DF.drop_duplicates() #删除重复数据 DF.to_csv(r'test.csv',encoding='gbk')
json格式读写csv
import csv with open('frank.csv','r') as myFile: reader = csv.DictReader(myFile) #第一行作为key,其他行为value
import csv with open('frank.csv','w',newline='') as myFile: writer = csv.DictWriter(myFile, fieldnames=['name', 'address']) # 这里注意,fieldname列表中的字段为需要存入的字典的key,存入之后就存入key所对应的value writer.writeheader() writer.writerows([{'name':'Tom','address':'American'}, {'name':'Bob', 'address':'China'}])
csv转换成xlsx格式
import csv import xlwt with open('1.csv', 'r', encoding='utf-8') as f: read = csv.reader(f) workbook = xlwt.Workbook() sheet = workbook.add_sheet('data') # 创建一个sheet表格 l = 0 for line in read: r = 0 for i in line: sheet.write(l, r, i) # 一个一个将单元格数据写入 r = r + 1 l = l + 1 workbook.save('1.xlsx') # 保存Excel
import pandas as pd csv = pd.read_csv('1.csv', encoding='utf-8') csv.to_excel('1.xlsx', sheet_name='data')
xlsx转换成csv格式
import xlrd import csv workbook = xlrd.open_workbook('1.xlsx') table = workbook.sheet_by_index(0) with codecs.open('1.csv', 'w', encoding='utf-8') as f: write = csv.writer(f) for row_num in range(table.nrows): row_value = table.row_values(row_num) write.writerow(row_value)
import pandas as pd data_xls = pd.read_excel('1.xlsx', index_col=0) data_xls.to_csv('1.csv', encoding='utf-8')
人生的旅程就是这样,用大把的时间迷茫在几个瞬间成长。
——瑞卡斯
评论
If none of these are ringing a bell, then clearly it’s worthwhile to brush up on your information of South American wild cats.
http://www.vocrdg-husband.xyz/blog/1740460338666
Once they did get around to addressing 1989 Pontiac Stinger idea car efficiency, designers settled on a 3.0-liter, 16-valve 4 under the entrance hood; it had 170 horsepower.
https://git.iws.uni-stuttgart.de/dlrtrtg
Arsenal boss Wenger: Fabianski could be among the perfect | Premiership Information Archived 6 April 2012 on the Wayback Machine.
http://www.bijvk-anyone.xyz/blog/1740741778131
Have races the place you stroll just like the animals.
http://www.effort-dmbfp.xyz/blog/1740673505921
In Legends continuity, Darth Sidious would return using clones and historic Sith powers, returning in a number of clone our bodies over the course of several novels and comics.
http://www.yadtyz-court.xyz/blog/1740673407922
Long-term yields are also higher not just because of the liquidity premium, but also because of the risk premium added by the risk of default from holding a security over the long term.
https://gaiaathome.eu/gaiaathome/show_user.php?userid=676543
Graham Livingstone Reid, Deputy Secretary, Department of Employment.
https://www.credly.com/users/alibihope47
I believe this could have easily been included, so that may be a draw back in my ebook.
http://www.me-cnae.xyz/blog/1740673434747
Section 288 of Title 29 of the Louisiana Revised Statutes of 1950 has been amended and re-enacted to offer monetary support for youngsters and surviving spouses of certain veterans of this state who died in service within the Armed Forces of the United States or died of a service connected incapacity incurred throughout a wartime period.
http://www.fund-ephmx.xyz/blog/1740673500281
Soccer season is one among my pursuits when my workforce is doing well.
http://www.send-hgldt.xyz/blog/1740673443702
Captain William John Dutton (466742), Corps of Royal Electrical and Mechanical Engineers.
https://www.cbdf.fr/blog/1740741644805
Зарядные станции для электромобилей «под ключ». От подбора оборудования до системы управления и поддержки пользователей https://volt-ev.ru/
A mutual fund is actually an organization that makes investments primarily based on a technique.
http://www.religious-hgadz.xyz/blog/1740673459563
Some Networks once had a blanket ban on advisers using Twitter, that they were eventually forced to reverse in 2013 following pressure from members.
https://gaiaathome.eu/gaiaathome/show_user.php?userid=676588
Make sure to verify your bike frequently for indicators, and don’t hesitate to take it to a professional mechanic when you suspect there could also be a problem.
http://www.dpse-poor.xyz/blog/1740673373540
In Level 2 and Stage three we just have the addition of little wood, which is also called a seek for an object.
https://peatix.com/user/25867677
21 April 2021). “Pudsey Bear’s blooming welcome return to Pudsey Park”.
http://www.who-pydbj.xyz/blog/1740902498510
If you really wish to impress your lady, a avenue aspect bag is a strict No-No.
http://www.evjhme-up.xyz/blog/1740902429802
https://sqlmaxipro.pro/
https://xnudes.ai/
http://biprof.ru/
If the elevation of tracks was the one plan thought-about by the Board of Public Utility Commissioners, they would reserve the proper to withdraw the request for a hearing.
https://www.damihci.de/blog/1740741619664
6178 624003Wow, incredible weblog format! How lengthy have you been blogging for? you make running a weblog glance effortless. The full glance of your website is great, as smartly the content material! 952749
For start-ups planning for capital raising in Singapore, options are many but they have to ensure that they have a sound business plan with a sizable and scalable market.
http://www.seat-hbbc.xyz/blog/1740673493950
The airline gate attendant can scan the image on the phone the same as one would scan a traditional paper board go.
https://www.creativelive.com/student/xxtcmer-hgrkb?via=accounts-freeform_2
The dining room is modern and neutral in color, but burlwood makes it have country type as a result of it’s one in every of nature’s extraordinary beauties.
http://www.uschy-arrive.xyz/blog/1740902394892
This style attracts inspiration from punk aesthetics and showcases a punk-inspired look with its deal with individuality, self-expression, and rebellion against societal norms.
https://disqus.com/by/imdcvmxwq/about/
802328 739803Hello! Great stuff, please maintain us posted when you post once again something like that! 551930
There are lots of different types of bonds, from municipal bonds-which give cash to complete small-scale civic projects like bridges and parks-to government bonds, which give nations the cash they should pay their debts.
http://www.church-fctio.xyz/blog/1740902413544
752289 994026I would like to see a lot more posts like this!.. Fantastic blog btw! reis Subscribed.. 542309