- 积分
- 6101
- 贡献
-
- 精华
- 在线时间
- 小时
- 注册时间
- 2011-12-4
- 最后登录
- 1970-1-1
|
登录后查看更多精彩内容~
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
读取一个txt文本,里面写了如图中格式的年月日时间等内容,
一行中年月日是确定的,时间的个数不确定,所以想通过循环写入excel,excel表格格式也如图中,
通过搜集大神们写的代码和自己编写,写出了如下代码(中间省去了写入数据的步骤),但是提示 return self._cell_values[rowx][colx] IndexError: list index out of range想求助一下一下该如何修改。
- import xlwt
- import xlrd
- f = xlwt.Workbook(encoding='utf-8') #新建工作簿
- sheet1 = f.add_sheet("大雾",cell_overwrite_ok=True) #新建sheet
- f.save(r'D:\forgdata\test.xlsx') #保存
- #设置表格样式
- def set_style(name,height,bold=False):
- style = xlwt.XFStyle()
- font = xlwt.Font()
- font.name = name
- font.bold = False
- font.color_index = 4
- font.height = height
- style.font = font
- return style
- #写Excel
- import xarray as xr
- def print2excel():
-
- lines = open("code.txt", 'r').readlines()
- x = int(1)
- for i in range(len(lines)):
- if i%2==0: #偶数行
- fields = lines[i].strip('\n')
- fields = fields.split(' ') #split data
- year = fields[0]
- month = fields[1]
- day = fields[2]
- row0 = ["年","月","日","时次(UTC)",'五角星','三角','方框','黑桃','备注']
- for k in range(0,len(row0)): #写第一行
- sheet1.write(0,k,row0[k],set_style('Times New Roman',220,True))
- for j in range(len(fields)):
- read = xlrd.open_workbook(r'D:\forgdata\test.xlsx')
- sheet2 = read.sheet_by_index(0)
- cell_x = sheet2.cell_value(x,0)
- int(j)
- n = j-3
- y = x+5*n-1
- if cell_x == 0:
- sheet1.write_merge(x,y,0,0,year)
- sheet1.write_merge(x,y,1,1,month)
- sheet1.write_merge(x,y,2,2,day)
- if j > 2:
- time=fields[j]
- j = j-1
- sheet1.write_merge(x,x+4,3,3,time)
- x = x+5
- ds1 = xr.open_dataset('d:/era_down/CDS%s%s%s'% (year,month,day)+'h.grib',engine='cfgrib')
- r = ds1['r']
- t = ds1['t']
- ds2 = xr.open_dataset('d:/era_down/CDS%s%s%s'% (year,month,day)+'s.grib',engine='cfgrib')
- else:
- continue
- else:
- pass
- x = x+1
- else:
- continue
- else:
- pass
- f.save('D:\forgdata\test.xlsx')
- if __name__ == '__main__':
- print2excel()
复制代码
|
|