python+openpyxl——读取/写入Excel(*.xlsx)

  • excel中行和列都是从1开始,但是python是从0开始;
  • 我的环境是pycharm + python3.7

openpyxl库

读取*.xlsx

  • 这里的输出是str
import openpyxl

def read_excel(excel_path = "test.xlsx"):
    workbook = openpyxl.load_workbook(excel_path)
    worksheet = workbook.get_sheet_by_name('Sheet1')
    data = ''
    for i in range(6, 8):
        for j in range(1, 11):
            cur = worksheet.cell(row=i, column=j).value
            data = data + cur
    return data

写入*.xlsx

  • 这里的输入是list
import openpyxl

def write_excel_xlsx(path, sheet_name, value):
#创建excel
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = sheet_name
#写入一个list:‘data’
	index = 0
    for i in range(10):
        for j in range(0, 10):
            sheet.cell(row=i+6, column=j+1, value=str(data[index]))
            index = index + 1
#存储excel        
    workbook.save(path)
    print("create *.xlsx file succeeful")

pandas

你可能感兴趣的:(python+openpyxl——读取/写入Excel(*.xlsx))