Python Excel 操作

# Python Excel 操作

# 当你从odoo附件中读取excel的时候需要做base64转码,因为odoo中存储的附件都是经过转码的
company = self.env['res.company'].sudo().browse(cid)
if not company.excel_file:
    return True
# 解析文件后缀
filename = company.excel_file_name
suffix = splitext(filename)[-1]
# 将文件内容写入临时文件中
fp = tempfile.NamedTemporaryFile(delete= False,suffix=".xlsx")
fp.write(binascii.a2b_base64(company.excel_file))
fp.seek(0)
file_name = fp.name
fp.close()

# 本文只涉及xls、xlsx、csv后缀的Excel文件
# xls是2003年的版本
# xlsx是2007年至今一直的版本,和xls的区别是,表格中插入了图片的话,xlsx对图片进行了压缩处理,所以一样的内容xls会比xlsx大很多。
# csv以逗号分隔的文本文件,便于兼容其他程序,只保存活动工作表

# 涉及模块
# xlrd 用于读取Excel文件,无写功能。仅支持xls格式
pip3 install xlrd
# xlwt 用于写Excel文件,无读功能。仅支持xls格式。当你只需要修改excel表格的时候,你调用保存你会发现图片丢失了。因为你用xlrd读取出来的内容只有文字并没有图片。图片还需你自己处理(还没研究)
pip3 install xlwt
# xlutils 用于读写Excel文件。仅支持xls格式。它只是集成了xlrd和xlwt两个模块。
pip3 install xlutils
# csv 用于读写csv后缀的Excel文件。和xlwt一样,只是修改的话会丢失图片
pip3 install csv # 好像自带就有
# openpyxl 用于读取/写入 Excel xlsx/xlsm 文件。该模块修改excel不会丢失图片
pip3 install openpyxl
# pandas 该模块是做数据分析用的,非常强大。修改excel表格的话也会丢失图片。但是好用的是,它支持所有excel格式
pip3 insytall pandas

# 例子:
# xlrd
import xlrd
book = xlrd.open_workbook("myfile.xls")
print("The number of worksheets is {0}".format(book.nsheets))
print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
print("Cell D30 is {0}".format(sh.cell_value(rowx=29, colx=3)))
for rx in range(sh.nrows):
    print(sh.row(rx))
    
# xlwt
import xlwt
from datetime import datetime

style0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on',
    num_format_str='#,##0.00')
style1 = xlwt.easyxf(num_format_str='D-MMM-YY')

wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')

ws.write(0, 0, 1234.56, style0)
ws.write(1, 0, datetime.now(), style1)
ws.write(2, 0, 1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))

wb.save('example.xls') 

# xlutils
import xlrd
import xlwt
from xlutils.copy import copy as xlscopy
workbook = xlrd.open_workbook(file_name, formatting_info=True)
writeworkbook = xlscopy(workbook)
# writeworkbook.save('/home/pc1/odoo14/local_shequ/python3/test123.xls')
for sheet_index in workbook.sheet_names():
    sheet_page = workbook.sheet_by_name(sheet_index)
    write_sheet_page = writeworkbook.get_sheet(sheet_index)
    rowMax = sheet_page.nrows
    colMax = sheet_page.ncols
    for row in range(rowMax):
        if row == 0:
            continue
        else:
            rows = sheet_page.row_values(row)
            for col in range(colMax):
                te_result = '修改的值'
                if te_result:
                    write_sheet_page.write(row,col,te_result)
writeworkbook.save(file_name)


# csv
import csv
file_reader = []
csv_reader = csv.reader(data_file, delimiter=',')
file_reader.extend(csv_reader)
for i in range(len(file_reader)):
  field = list(map(str, file_reader[i]))
  values = dict(zip(keys, field))
  if values:
    if i == 0:
      continue
    else:
      values.update({
                        'Part Type' : field[0],
                        })
      lvalues.append(values)
      
# openpyxl
# 文档:https://openpyxl.readthedocs.io/en/stable/
# 1
from  openpyxl import  load_workbook
wb = load_workbook(file_name)
for sheet_name in wb.sheetnames:
    ws = wb[sheet_name]
    for row in ws.rows:
        for cell in row:
            te_result = '你要修改的值'
            if te_result:
                cell.value = te_result
wb.save(file_name)

# 2
from openpyxl import Workbook
wb = Workbook()

# grab the active worksheet
ws = wb.active

# Data can be assigned directly to cells
ws['A1'] = 42

# Rows can also be appended
ws.append([1, 2, 3])

# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()

# Save the file
wb.save("sample.xlsx")

 

posted @ 2021-12-28 11:13  看一百次夜空里的深蓝  阅读(287)  评论(0编辑  收藏  举报