Create a new Excel uses openpyxl and xlrd in python and copy the original table data into a new table

Create a new Excel uses openpyxl and xlrd in Python and copy the original table data into a new table

New beginning

Born arts, economics, nearly Lent is purely interested in this as a school. Long before going to learn Python, but has been stuck in installed Python, these days, more free, began to experience a lot of pit from the most basic self-study, during which many of them are relying on CSDN study notes fill, so also here to open a complete record of the learning process of a 0 white base, but also hope to have a little help newcomers.
Because of their work, dealing more with Excel, so from a combination of Python and Excel begin.

import xlrd
import openpyxl
#import不可以大写,xlwt只能解决xls,xlsx需要用openpyxl,安装代码:CMD下,不需
#进入python安装直接使用pip3 install xlrd/openpyxl
#安装完,如果在CMD里可以import,但在pycharm里面不行且提示ModuleNotFoundError: 
#No module named 'xlrd',则需要到Setting - Project Interpreter里面选择,点
#下拉菜单,看看哪个带着你刚安装的模块,就选哪个。
source_xls = [(r'c:\1\1.xlsx'),(r'c:\1\2.xlsx')]
#罗列出所有需要被复制的工作簿
#这个是别人的代码我复制过来,我猜这里的r代表路径,最后的save也证实了我的猜测
data = []
#[]代表的是空的可变list,这个表示把data设为一个空的可变list
for i in source_xls:
    wb = xlrd.open_workbook(i)
    for sheet in wb.sheets():
        for rownum in range(sheet.nrows):
            data.append(sheet.row_values(rownum))
#.append代表在原有数列的最后,插入括号中的数据
#i代表两个不同的工作簿
#这里有的属性用'.',有的属性用'_',根据我自己的猜测,应该是动作,比如open用','
#如果是本身的属性,比如sheet之类,就用'_'
#这里推荐用Pycharm来写代码,毕竟对新手而言,界面毕竟友好,也有一些提示
wk = openpyxl.Workbook()
#创建一个新的表格,这里要注意,Workbook里的W一定要大写,我开始用的是小写,总显示
#错误,在这里花了好久找问题
wkts = wk.active
#在创建工作簿的时候,会创建一个默认的工作表sheet,这里表示使用当前的活跃工作表
#如果不想用默认的工作表,代码为 wkts=wk.create_sheet("sheet_name")
for i in range(len(data)):
    for j in range(len(data[i])):
        wkts.cell(i+1,j+1,data[i][j])
wk.save(r'c:\1\Excel_name.xlsx')
# 为什么要用i+1 和 j+1呢?因为对range来说,默认是0开始的,也就是第一个数字是0,
#而cell()这个函数,他的行和列必须是个至少为1的整数,所以要用+1
#有人会问,那我在range的时候,就用range(1,len(data))行不行呢?
#答案是不行,因为这样就等于少了0行代表的那部分数据,通常是标题不见了
#最后save()函数,前面也要加r,才能显示路径,否则会把引号里所有的都认为是文件名
Released eight original articles · won praise 3 · Views 5584

Guess you like

Origin blog.csdn.net/cwjcw81/article/details/83071045