xlrd and xlsxwriter operate excel table

Introduction

  • Combine your usual examples
    • Reading excel with xlrdmodule
    • Set cell style and write excel file xlsxwriteris enough!

xlrd usage

import xlrd
book = xlrd.open_workbook('data.xlsx')
sheet1 = book.sheets()[0]
nrows = sheet1.nrows
print('表格总行数',nrows)
ncols = sheet1.ncols
print('表格总列数',ncols)
row3_values = sheet1.row_values(2)
print('第3行值',row3_values)
col3_values = sheet1.col_values(2)
print('第3列值',col3_values)
cell_3_3 = sheet1.cell(2,2).value
print('第3行第3列的单元格的值:',cell_3_3)

xlsxwriter usage

Trick 1: Use python to bold the specified text in the excel cell and mark it in red

import xlsxwriter
out_path = 'test.xlsx'
workbook = xlsxwriter.Workbook(out_path)
worksheet = workbook.add_worksheet('sheet1')
bold_red = workbook.add_format({
    
    'bold': True, 'color': 'red'})

worksheet.write_rich_string('A1',
                            '这是一个',
                            bold_red, '测试',
                            ',哈哈哈')

workbook.close()

Write file

Write line by line

import xlsxwriter
res_file = 'labeled_data_consistency.xlsx'
workbook = xlsxwriter.Workbook(os.path.join(cur_dir, res_file))
booksheet = workbook.add_worksheet('Sheet1')

booksheet.write_row('A1', head)
bold_red = workbook.add_format({
    
    'bold': True, 'color': 'red'})
for i in range(2, len(data_list)+2):
    line = 'A' + str(i)  # 从第二行开始,第一行是表头
    booksheet.write_row(line, data_list[i-2])

Write cell by cell

import xlsxwriter
res_file = 'labeled_data_consistency.xlsx'
workbook = xlsxwriter.Workbook(os.path.join(cur_dir, res_file))
booksheet = workbook.add_worksheet('Sheet1')

booksheet.write_row('A1', head)
bold_red = workbook.add_format({
    
    'bold': True, 'color': 'red'})
for i in range(2, len(data_list)+2):
    # line = 'A' + str(i)  # 从第二行开始,第一行是表头
    # booksheet.write_row(line, data_list[i-2])
    one_list = data_list[i-2]
    for j in range(12):
        if one_list[j]:  # 数据非空,才准备写入单元格
            booksheet.write_rich_string(i, j, one_list[j])
workbook.close()

Guess you like

Origin blog.csdn.net/m0_38024592/article/details/109483583