- import xlrd
- import xlwt
- from datetime import date, datetime
- def read_excel():
- # 1 打开文件
- workbook = xlrd.open_workbook('表格1.xlsx')
- # 2 获取sheet的名字
- sheet2_name = workbook.sheet_names()[0]
- print("获取sheet的名字", sheet2_name)
- # 3 获得sheet的内容
- # 根据sheet索引或者名称获取sheet内容
- sheet2 = workbook.sheet_by_index(0) # sheet索引从0开始
- # sheet2 = workbook.sheet_by_name('sheet2')
- # 4 sheet的名称,行数,列数
- print(sheet2.name, sheet2.nrows, sheet2.ncols)
- # 5 获取整行和整列的值(数组)
- # rows = sheet2.row_values(2) # 获取第二行内容 list
- # cols = sheet2.col_values(4) # 获取第四列内容 list
- # print(rows, cols)
- # 6 获取单元格内容
- print(sheet2.cell(1, 0).value)
- print(sheet2.cell_value(1, 0))
- print(sheet2.row(1)[0].value)
- # 7 获取单元格内容的数据类型
- print(sheet2.cell(1, 0).ctype)
- # 其它
- # sheet1 = wb.sheet_by_index(0) # 通过索引获取表格
- # sheet2 = wb.sheet_by_name('年级') # 通过名字获取表格
- # print(sheet1, sheet2)
- # print(sheet1.name, sheet1.nrows, sheet1.ncols)
- def write_excel():
- """书写数据是以sheet为单位的,所以首先要创建新的sheet"""
- # 0 创建对象
- f = xlwt.Workbook()
- # 1 创建新的sheet了 # 参数1:名字,参数2:是否可以覆盖写入
- sheet1 = f.add_sheet('2018年账目', cell_overwrite_ok=True)
- # 2 写入函数 sheet1.write(x, y, str)
- row0 = ['月', '日', '凭证编号 ', '摘要', '对应科目', '借方金额', ' 贷方金额', '余额']
- colum0 = [12, 12, 12]
- colum1 = [2, 3, 4]
- colum2 = [20181202, 20181203, 20181204]
- colum3 = ['A原料公司进货款100万', 'B经销公司货款30万', 'c经销公司货款30万']
- colum4 = ['成本', '销售', '销售']
- # 写第一行
- for i in range(0, len(row0)):
- sheet1.write(0, i, row0[i], set_style('Times New Roman', 220, True))
- # 写第一列
- for i in range(0, len(colum0)):
- sheet1.write(i + 1, 0, colum0[i], set_style('Times New Roman', 220, True))
- # 写第一列
- for i in range(0, len(colum1)):
- sheet1.write(i + 1, 1, colum1[i], set_style('Times New Roman', 220, True))
- # 写第一列
- for i in range(0, len(colum2)):
- sheet1.write(i + 1, 2, colum2[i], set_style('Times New Roman', 220, True))
- # 写第一列
- for i in range(0, len(colum3)):
- sheet1.write(i + 1, 3, colum3[i], set_style('Times New Roman', 220, True))
- # 写第一列
- for i in range(0, len(colum4)):
- sheet1.write(i + 1, 4, colum4[i], set_style('Times New Roman', 220, True))
- # 3 合并单元格写入
- # sheet1.write_merge(7, 8, 2, 4, 'ceshi')
- # 合并第8-9行,第3-5列,写入ceshi
- # sheet1.write_merge('对应科目', '原料', '销售')
- # 4 添加超链接
- # n = "HYPERLINK"
- # sheet1.write_merge(9, 9, 2, 8, xlwt.Formula(n + '("http://www.baidu.com")'), set_style('Arial', 300, True))
- f.save("表格1.xlsx")
- print("done")
- def set_style(name, height, bold=False):
- style = xlwt.XFStyle() # 初始化样式
- font = xlwt.Font() # 为样式创建字体
- font.name = name # 'Times New Roman'
- font.bold = bold
- font.color_index = 4
- font.height = height
- style.font = font
- return style
- if __name__ == '__main__':
- read_excel()
- write_excel()
复制代码 |
|