1 背景
最近在整理气象数据,想把xls的数据转为csv格式方便后续用python进行shp的转化,故引出了这个问题。查看了相关资料,有两种方法可供选择,一种是按列,一种是按行,这个可以根据自己的数据来选择,记录如下。
1.1 数据源:
我使用的气象数据是已经经过了处理的,xls的界面如下所示:
2 参考文献
《python数据写入CSV》
《python读取excel某列数据》
3 代码
3.1 用列写入
import os
import time
import logging
import xlrd
import csv
import xlrd
import pandas as pd
outputflder=r"E:\excel\TA\4. csv\2002"
worksheet = xlrd.open_workbook(r'E:\excel\TA\3. delblank\2002\ deblank 2002 01.xls')
sheet_names= worksheet.sheet_names()
print(sheet_names)
for sheet_name in sheet_names:
sheet = worksheet.sheet_by_name(sheet_name)
rows = sheet.nrows # 获取行数
cols = sheet.ncols # 获取列数
#如果太多了,这里可以用一下for循环
col1 = sheet.col_values(0) # 获取第二列内容, 数据格式为此数据的原有格式(原:字符串,读取:字符串; 原:浮点数, 读取:浮点数)
col2 = sheet.col_values(1)
col3 = sheet.col_values(2)
col4 = sheet.col_values(3)
col5 = sheet.col_values(4)
col6 = sheet.col_values(5)
col7 = sheet.col_values(6)
col8 = sheet.col_values(7)
col9 = sheet.col_values(8)
#use pandas
#write date by using the form of dict
df= pd.DataFrame({'station':col1,'lat':col2,'lon':col3,'dem':col4,'year':col5,'month':col6,'day':col7,'Ta':col8,'Kelvins':col9})
outputfile=outputflder+'\\2002'+sheet_name+'.csv' #命名
df.to_csv(outputfile,index=False)
print("OK")
得到的结果如下图所示,会发现多出了一行表头,主要是pd.DataFrame这里要写上表头:
3.2 用行写入:
import csv
from openpyxl import load_workbook
import xlrd
import xlwt
from xlutils.copy import copy
import os.path
outputflder=r"E:\excel\TA\4.1 CSV"
file=r"E:\excel\TA\3. delblank\2002\ deblank 2002 01.xls" #要转换的xls文件
worksheet=xlrd.open_workbook(file,formatting_info=True)
sheet_names= worksheet.sheet_names()
print(sheet_names)
for sheet_name in sheet_names:
sheet = worksheet.sheet_by_name(sheet_name)
rows = sheet.nrows # 获取行数
cols = sheet.ncols # 获取列数,尽管没用到
rowValueList=[]
for i in range(0,rows): #遍历行
row_data = sheet.row_values(i) #第i行数据
rowValueList.append(row_data) #把所有行都加进去
#use pandas
#write date by using the form of dict
outputfile=outputflder+'\\2002'+sheet_name+'.csv'
with open(outputfile, "w") as csvfile:
writer = csv.writer(csvfile,lineterminator='\n')
writer.writerows(rowValueList)
print("OK")
得到的结果是这样的: