Python合并多个Excel数据
安装模块
1、找到对应的模块 http://www.python-excel.org/
2、用pip install 安装
pip install xlrd
pip install XlsxWriter
pip list查看
XlsxWriter示例
1 import xlsxwriter 2 3 # 创建一个工作簿并添加一个工作表 4 workbook = xlsxwriter.Workbook("demo.xlsx") 5 worksheet = workbook.add_worksheet() 6 7 # 设置列宽 8 worksheet.set_column("A:A", 20) 9 10 # 设置格式 11 bold = workbook.add_format({"bold": True}) 12 13 # 设置单元格的值 14 worksheet.write("A1", "Hello") 15 16 # 带格式的单元格 17 worksheet.write("A2", "World") 18 19 # 写一些数字,用行列标识 20 worksheet.write(2, 0, 123) 21 worksheet.write(3, 0, 123.456, bold) 22 23 # 插入一张图片 24 worksheet.insert_image("B5", "C:/Users/Cheng/Desktop/1.png") 25 26 # 关闭文件流 27 workbook.close()
运行结果如下:
合并Excel数据
思路
Excel是由行和列组成的,所以这里将所有文件中的所有sheet中的数据读取出来组成一个二维数组,然后再写入新的Excel
代码
1 import xlrd 2 import xlsxwriter 3 4 source_xls = ["D:/python/1.xlsx", "D:/python/2.xlsx"] 5 target_xls = "D:/python/3.xlsx" 6 7 # 读取数据 8 data = [] 9 for i in source_xls: 10 wb = xlrd.open_workbook(i) 11 for sheet in wb.sheets(): 12 for rownum in range(sheet.nrows): 13 data.append(sheet.row_values(rownum)) 14 print(data) 15 # 写入数据 16 workbook = xlsxwriter.Workbook(target_xls) 17 worksheet = workbook.add_worksheet() 18 font = workbook.add_format({"font_size":14}) 19 for i in range(len(data)): 20 for j in range(len(data[i])): 21 worksheet.write(i, j, data[i][j], font) 22 # 关闭文件流 23 workbook.close()
运行结果
体会
刚开始学习Python,可能是由于看惯了Java代码的缘故吧,初学起来感觉语法怪怪的,跟Java有些类似,又感觉和JavaScript,Perl这种有点像。。。
不愧是,面向对象的、解释型的高级编程语言!!!