概述
在使用Python處理數據的過程中常常需要讀取或寫入Excel表格,本文簡要介紹使用xlrd讀取Excel表格數據及使用XlsxWriter將數據寫入到指定的sheet中。
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()