Python 操做Excel

概述

在使用Python处理数据的过程当中经常须要读取或写入Excel表格,本文简要介绍使用xlrd读取Excel表格数据及使用XlsxWriter将数据写入到指定的sheet中。excel


Code Sample
  • Excel读操做示例
#coding=utf-8

import xlrd

#路径前加 r,读取的文件路径
file_path = r'c:/Users/yuvmtest/Desktop/testdata.xlsx'

#获取数据
data = xlrd.open_workbook(file_path)

#获取sheet
table = data.sheet_by_name('Sheet0')

#获取总行数
nrows = table.nrows
#获取总列数
ncols = table.ncols

print("总行数: %d,总列数: %d" % (nrows, ncols))

#获取一行的数值,例如第2行
rowvalue = table.row_values(2)

#获取一列的数值,例如第3列
col_values = table.col_values(3)

#获取一个单元格的数值,例如第2行第3列
cell_value = table.cell(2, 3).value

print(rowvalue)
print(col_values)
  • Excel 写操做示例
# excel 写操做示例
import xlsxwriter

workbook = xlsxwriter.Workbook('d:\yuexceltest.xlsx')  # 建立一个Excel文件
worksheet = workbook.add_worksheet('test1')            # 建立一个sheet

title = [U'列名1', U'列名2']                         # 表格title
worksheet.write_row('A1', title)                    # title写入Excel

headings = ['a', 'b', 'c', 'd']
data = [
    [1, 2, 3],
    [2, 4, 6],
    [3, 6, 9]
]

# 按行插入数据
worksheet.write_row('A4', headings)
# 按列插入数据

worksheet.write_column('A5', data[0])
worksheet.write_column('B5', data[1])
worksheet.write_column('C5', data[2])

# 插入多行数据

for i in range(10):
    row = i + 8
    row_number = 'A' + str(row)
    worksheet.write_row(row_number, str(row*2))

workbook.close()
写操做效果展现

image


参考

Creating Excel files with Python and XlsxWritercode

相关文章
相关标签/搜索