wangyaqi 2018-07-16
安装模块
1、找到对应的模块 http://www.python-excel.org/
2、用pip install 安装
pip install xlrd pip install XlsxWriter
pip list查看
XlsxWriter示例
import xlsxwriter # 创建一个工作簿并添加一个工作表 workbook = xlsxwriter.Workbook("demo.xlsx") worksheet = workbook.add_worksheet() # 设置列宽 worksheet.set_column("A:A", 20) # 设置格式 bold = workbook.add_format({"bold": True}) # 设置单元格的值 worksheet.write("A1", "Hello") # 带格式的单元格 worksheet.write("A2", "World") # 写一些数字,用行列标识 worksheet.write(2, 0, 123) worksheet.write(3, 0, 123.456, bold) # 插入一张图片 worksheet.insert_image("B5", "C:/Users/Cheng/Desktop/1.png") # 关闭文件流 workbook.close()
运行结果如下:
合并Excel数据思路
Excel是由行和列组成的,所以这里将所有文件中的所有sheet中的数据读取出来组成一个二维数组,然后再写入新的Excel
代码
import xlrd import xlsxwriter source_xls = ["D:/python/1.xlsx", "D:/python/2.xlsx"] target_xls = "D:/python/3.xlsx" # 读取数据 data = [] 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)) print(data) # 写入数据 workbook = xlsxwriter.Workbook(target_xls) worksheet = workbook.add_worksheet() font = workbook.add_format({"font_size":14}) for i in range(len(data)): for j in range(len(data[i])): worksheet.write(i, j, data[i][j], font) # 关闭文件流 workbook.close()
运行结果
体会
刚开始学习Python,可能是由于看惯了Java代码的缘故吧,初学起来感觉语法怪怪的,跟Java有些类似,又感觉和JavaScript,Perl这种有点像。。。
总结