zoukankan      html  css  js  c++  java
  • (copy)python操作excel

     

    python操作excel除了读就是写。

    1 从读开始 xlrd  下载地址:http://pypi.python.org/pypi/xlrd

    导入:import xlrd

    打开excel: file = xlrd.open_workbook('demo.xls')

    查看文件中包含sheet的名称:file.sheet_names()

    得到第一个工作表,或者通过索引顺序 或 工作表名称
    sheet = file.sheets()[0]
    sheet = file.sheet_by_index(0)
    sheet = file.sheet_by_name(u'Sheet1')

    获取行数和列数
    nrows = sheet.nrows
    ncols = sheet.ncols

    循环行,得到索引的列表
    for rownum in range(sheet.nrows):
        print sheet.row_values(rownum)

    获取整行和整列的值(数组)
    sheet.row_values(i)
    sheet.col_values(i)

    单元格(索引获取)
    cell_A1 = sheet.cell(0,0).value
    cell_C4 = sheet.cell(2,3).value

    分别使用行列索引
    cell_A1 = sheet.row(0)[0].value
    cell_A2 = sheet.col(1)[0].value

    2 写 xlwt 下载地址:http://pypi.python.org/pypi/xlrd

    导入xlwt import xlwt

    新建一个excel文件

    file = xlwt.Workbook() #注意这里的Workbook首字母是大写,无语吧

    新建一个sheet

    sheet = file.add_sheet('sheet name')

    写入数据sheet.write(行,列,value)

    sheet.write(0,0,'test')

    如果对一个单元格重复操作,会引发
    returns error:
    # Exception: Attempt to overwrite cell:
    # sheetname=u'sheet 1' rowx=0 colx=0

    所以在打开时加cell_overwrite_ok=True解决

    sheet = file.add_sheet('sheet name',cell_overwrite_ok=True)

    保存文件

    file.save('demo.xls')

    另外,使用style

    style = xlwt.XFStyle() #初始化样式

    font = xlwt.Font() #为样式创建字体

    font.name = 'Times New Roman'

    font.bold = True

    style.font = font #为样式设置字体

    sheet.write(0, 0, 'some bold Times text', style) # 使用样式

    xlwt 允许单元格或者整行地设置格式。还可以添加链接以及公式。

    源代码中的模块:

      dates.py, 展示如何设置不同的数据格式

      hyperlinks.py, 展示如何创建超链接  

      merged.py, 展示如何合并格子

      row_styles.py, 展示如何应用Style到整行格子中.

  • 相关阅读:
    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4: install (default-install) on project authorizationManagement-service: Failed to install metadata com.dmsdbj.itoo:autho
    IEDA中使用阿里插件Alibaba Cloud Toolkit和Arthas(阿尔萨斯)
    ECS与EDAS什么意思?
    【学习笔记】随机深林
    R概率分布函数使用小结
    KNN
    K-MEANS
    mac下安装face_recognition
    linux下配置face_recognition
    springboot-actuator
  • 原文地址:https://www.cnblogs.com/ylx900/p/9330705.html
Copyright © 2011-2022 走看看