import xlrd file_path = 'example.xlsx' work_book = xlrd.open_workbook(file_path) sheet_names = work_book.sheet_names() # 打印所有的工作表的名称 work_sheet = work_book.sheet_by_name(sheet_names[0]) # 通过表名打开对应的工作表 work_sheet = work_book.sheet_by_index(0) # 通过表名的索引打开工作表 row_data = work_sheet.row(0) # 第一行的数据,存放在一个列表种.包含名称和数据类型 '''[text:'ankit', text:'A', text:'B', text:'C']''' row_data = work_sheet.row_values(rowx=0, start_colx=0, end_colx=None) # 只包含值 '''['ankit', 'A', 'B', 'C']''' print('第一行的数据:',row_data) colom_data = work_sheet.col(0) # 第一列的数据 colom_data = work_sheet.col_values(colx=0, start_rowx=0, end_rowx=None) print('第一列的数据:', colom_data) num_cols = work_sheet.ncols # 总共有多少列数据 num_rows = work_sheet.nrows # 总共多少行数据 print(f'总共{num_rows}行{num_cols}数据!') # 逐行打印所有的数据 for row_idx in range(0, work_sheet.nrows): # 总共多少行数据 print(f'第{row_idx}行') for col_idx in range(0, num_cols): cell_obj = work_sheet.cell(row_idx, col_idx) # # 每一个单元格中的数据 print(cell_obj.value)
import xlwt work_book = xlwt.Workbook() # 创建一个命名为Sheet1的工作表 sheet1 = work_book.add_sheet('Sheet1') # 往第一列的每行写入数据 sheet1.write(1, 0, 'A') sheet1.write(2, 0, 'B') sheet1.write(3, 0, 'C') sheet1.write(4, 0, 'D') # 往第一行的每列写入数据 sheet1.write(0, 1, 'a') sheet1.write(0, 2, 'b') sheet1.write(0, 3, 'c') sheet1.write(0, 4, 'd') work_book.save('example2.xlsx')
from xlutils.copy import copy from xlrd import open_workbook exist_path = 'example2.xlsx' old_workBook = open_workbook(exist_path, formatting_info=True) # read_sheet = old_workBook.sheet_by_index(0) # 只copy第一张工作表 # print(read_sheet.cell(0,1).value) # print(read_sheet.nrows) # print(read_sheet.ncols) work_book = copy(old_workBook) write_sheet = work_book.get_sheet(0) write_sheet.write(0,0,'python') # 在第0行0列追加写入 work_book.save('new_example.xlsx')
参考资料:
https://blogs.harvard.edu/rprasad/2014/06/16/reading-excel-with-python-xlrd/
https://www.codespeedy.com/writing-excel-file-using-xlwt-in-python/
https://stackoverflow.com/questions/2725852/writing-to-existing-workbook-using-xlwt