python操作excel

在python中,对excel表格

wlrd 读取excel表中的数据 
xlwt 创建一个全新的excel文件,然后对这个文件进行写入内容以及保存。 
xlutils 读入一个excel文件,然后进行修改或追加,不能操作xlsx,只能操作xls。

一、读excel表

读excel要用到xlrd模块
1、导入模块

import xlrd

2、打开excel文件,表格从0计数

import xlrd
excel_calss = xlrd.open_workbook(r'C:UsersjokerDesktopecs.xlsx')
sheet = excel_calss.sheets()[0]              # 通过索引顺序获取
sheet = excel_calss.sheet_by_index(0)        # 通过索引顺序获取
sheet = excel_calss.sheet_by_name(u'Sheet1') # 通过名称获取

3、获取表格行数和列数,行,列从0计数

import xlrd
excel_calss = xlrd.open_workbook(r'C:UsersjokerDesktopecs.xlsx')
sheet = excel_calss.sheet_by_index(0)        # 通过索引顺序获取
num_rows = sheet.nrows       # 行数 int
num_cols = sheet.ncols       # 列数 int

4、获取表格整行和整列的值,以列表形式返回,行,列从0计数

sheet_row18 = sheet.row_values(18)  # 获取行得内容,列表形式
sheet_row19 = sheet.row_values(19)
sheet_col1 = sheet.col_values(1)    # 获取列内容,列表形式
sheet_col2 = sheet.col_values(2)

5、获取表格单元格数据

cell_A1 = sheet.cell(0,0).value     # 指定单元格A1数据
cell_5145 = sheet.row(19)[1].value  # 使用行索引确定单元格数据
cell_5145 = sheet.col(1)[1].value   # 使用列索引确定单元格数据

二、写excel操作

1、导入模块

import xlwt

2、创建workbook

workbook = xlwt.Workbook(encoding='utf-8', style_compression=0)
encoding:设置字符编码,一般要这样设置:w = Workbook(encoding=’utf-8’),就可以在excel中输出中文了。默认是ascii 
style_compression:表示是否压缩,不常用 

3、创建一个sheet对象,一个sheet对象对应Excel文件中的一张表格

sheet = workbook.add_sheet('班级', cell_overwrite_ok=True)
其中的joker是这张表的名字,cell_overwrite_ok,表示是否可以覆盖单元格,其实是Worksheet实例化的一个参数,默认值是False 

4、向表中添加数据

sheet.write(0, 0, '名称')  # 其中的'0-行, 0-列'指定表中的单元,'名称'是向该单元写入的内容
sheet.write(0, 1, '年龄')
username = 'joker'
sheet.write(1, 0, username ) 
age = '18'
sheet.write(1, 1, age)

5、保存

workbook.save(r'C:UsersjokerDesktopecs.xls')

三、追加数据

import xlrd
import xlutils.copy
excel_calss = xlrd.open_workbook(r'C:UsersjokerDesktopecs.xls')
excel_copy = xlutils.copy.copy(excel_calss)
sheet=excel_copy.get_sheet(0)
sheet.write(0,2,'性别')
excel_copy.save(r'C:UsersjokerDesktopecs.xls')
# 追加前:
# 姓名 年龄
# 追加后:
# 姓名 年龄 性别

四、csv转化为excel,PYTHON在生成excel的时候注意是文件扩展名要以2003 为准,保存文件名扩展名改成 xls

import csv
import xlwt

workbook = xlwt.Workbook()
sheet2 = workbook.add_sheet("Sheet 2", cell_overwrite_ok=True)
file = open(r'D:label.csv')
lines = csv.reader(file)
r = 0
for line in lines:
    col = 0
    for c in line:
        sheet2.row(r).write(col,c, style=xlwt.Style.default_style)
        #print(c,end=' ')
        col += 1
    r += 1
    sheet2.flush_row_data()
file.close()   
workbook.save("csv2excel.xls")

五、 EXCEL通过请求下载

from io import BytesIO
import xlsxwriter

def filexlsx(request):
    url = "拼接字符串"
    time_str = str(datetime.datetime.today().time()).split('.')[0]
    date_str = str(datetime.datetime.today().date())
    filename_str = date_str + '_' + time_str+'.xlsx'
    dataExecl = Page_data.dataexcel # 数据
    if dataExecl:
        x_io = BytesIO()
        work_book = xlsxwriter.Workbook(x_io)
        work_sheet = work_book.add_worksheet("uid_video")
        work_sheet.write(0, 0, 'uid')  # 其中的'0-行, 0-列'指定表中的单元,'uid'是向该单元写入的内容
        work_sheet.write(0, 1, 'url_video')

        hang = 0
        for key in dataExecl:
            if dataExecl.get(key):
                hang += 1
                line = 0
                work_sheet.write(hang, line, key)
                line = 1
                for value in dataExecl[key]:
                    work_sheet.write(hang, line, url + key + '/' + value)
                    hang += 1
            else:
                pass

        work_book.close()
        res = HttpResponse()
        res["Content-Type"] = "application/octet-stream"
        res["Content-Disposition"] = "filename=%s" % filename_str
        res.write(x_io.getvalue())
        return res
    else:
        return HttpResponse('500')
原文地址:https://www.cnblogs.com/jokerbj/p/10441136.html