请选择 进入手机版 | 继续访问电脑版

Hello Mat

 找回密码
 立即注册
查看: 4815|回复: 0

读取和写入Excel

[复制链接]

1294

主题

1520

帖子

110

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22633
发表于 2017-7-19 20:52:33 | 显示全部楼层 |阅读模式

环境:win7系统、64bit、CPU、Anaconda3-4.2.0-Windows-x86_64
软件:Anaconda3-4.2.0-Windows-x86_64、VS2013

读取和写入Excel:
xlrd和xlwt,习惯用array来操作
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Jul 19 19:43:01 2017

  4. @author: Administrator
  5. """

  6. import xlrd
  7. import numpy
  8. from matplotlib import pyplot as plt
  9. from mpl_toolkits.mplot3d import Axes3D
  10. excel = xlrd.open_workbook('ysw.xlsx');
  11. # 获取第一个sheet
  12. sheet1 = excel.sheets()[0]

  13. # 获取数据行数
  14. nrows = sheet1.nrows;
  15. # 获取数据列数
  16. ncols = sheet1.ncols;

  17. # 获取第3列的数据,数据的列数从0开始计数
  18. value = sheet1.col_values(2)
  19. # 获取第3行的数据,数据的行列数从0开始计数
  20. value1 = sheet1.row_values(2)

  21. # 获取制定行列的数据
  22. row = 2;
  23. col = 2;
  24. value2 = sheet1.cell(row,col).value;

  25. # 获取整个excel表格数据
  26. data = [[0 for x in range(ncols)]]*(nrows-1)
  27. data = numpy.array(data,dtype='float64');
  28. for i in range(nrows-1):
  29.     data[i][0] = sheet1.cell(i+1,0).value;
  30.     data[i][1] = sheet1.cell(i+1,1).value;
  31.     data[i][2] = sheet1.cell(i+1,2).value;
  32.     data[i][3] = sheet1.cell(i+1,3).value;
  33.     data[i][4] = sheet1.cell(i+1,4).value;

  34. # 转置
  35. x,y,z = data.T[0], data.T[1],data.T[2]
  36. fig = plt.figure();
  37. # 创建一个三维的视图
  38. ax = plt.subplot(111,projection='3d');
  39. # 散点图
  40. ax.scatter(x,y,z,c='b');
  41. ax.set_xlabel("x")
  42. ax.set_ylabel("y")
  43. ax.set_zlabel("z")
  44. ax.set_title("scatter diagram")
  45. plt.show()



  46. # 将data写入Excel
  47. # 创建一个book
  48. import xlwt
  49. book = xlwt.Workbook(encoding='utf-8', style_compression=0);
  50. # 在book里面添加一个sheet
  51. sheet = book.add_sheet('halcom.cn',cell_overwrite_ok = True);

  52. # 写入数据
  53. sheet.write(0,0,'www.halcom.cn');

  54. for i in range(12):
  55.     sheet.write(i+1,0,data[i][0]);
  56.     sheet.write(i+1,1,data[i][1]);         
  57.     sheet.write(i+1,2,data[i][2]);
  58.     sheet.write(i+1,3,data[i][3]);
  59.     sheet.write(i+1,4,data[i][4]);
  60.                
  61. book.save('D:\Deep_learning_TensorFlow_python\Learning_DayByDay\Excel\data.xls')
复制代码

book.save需要写为.xls后缀的Excel。

算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Python|Opencv|MATLAB|Halcom.cn ( 蜀ICP备16027072号 )

GMT+8, 2024-4-18 08:31 , Processed in 0.204136 second(s), 21 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表