python 操作Excel 学习笔记

# encoding=utf-8
import numpy as np
import pandas as pd
import sys
import xlrd, xlwt

path = 'd:data/'
wb = xlwt.Workbook()
print wb
wb.add_sheet('first_sheet', cell_overwrite_ok=True)
wb.get_active_sheet()

ws_1 = wb.get_sheet(0)
print 'ws_1:=\n', ws_1
ws_2 = wb.add_sheet('second_sheet')
data = np.arange(1, 65).reshape((8, 8))
#  对单元格写入值
ws_1.write(0, 0, 100)
print 'data:=\n', data
print 'data.shape[0]:=\n', data.shape[0]
print 'data.shape[1]:=\n', data.shape[1]
for c in range(data.shape[0]):
    for r in range(data.shape[1]):
        ws_1.write(r, c, data[c, r])
        ws_2.write(r, c, data[r, c])
wb.save(path + 'workbook.xls')

print 'test'
# encoding=utf-8
import xlrd, xlwt
import pandas as pd
import sys

path = 'd:data/'
#  从工作簿中读取
book = xlrd.open_workbook(path + 'workbook.xls')
print 'book:=\n', book
print 'book.sheet_names():=', book.sheet_names()
sheet_1 = book.sheet_by_name('first_sheet')
sheet_2 = book.sheet_by_index(1)
print 'sheet_1:=\n', sheet_1
print 'sheet_2:=\n', sheet_2
print 'sheet_1.name:=', sheet_1.name
print 'sheet_2.name:=', sheet_2.name
print 'sheet_1.ncols:=\n', sheet_1.ncols
print 'sheet_1.nrows:=\n', sheet_1.nrows
c1 = sheet_1.cell(0, 0)
print 'c1.value:=\n', c1.value
print 'c1.ctype:=\n', c1.ctype
row3 = sheet_2.row(3)
print 'row3:=\n', row3

col3 = sheet_2.col(3)
print 'col3:=\n', col3
sheet1_col3 = sheet_1.col_values(3, start_rowx=3, end_rowx=7)
print 'sheet1_col3:=\n', sheet1_col3
sheet1_row3 = sheet_1.row_values(3, start_colx=3, end_colx=7)
print 'sheet1_row3:=\n', sheet1_row3
for c in range(sheet_1.ncols):
    for r in range(sheet_1.nrows):
        print '%i' % sheet_1.cell(r, c).value,
    print
# 使用pandas 读取
xls_file = pd.ExcelFile(path + 'workbook.xls')
table = xls_file.parse('first_sheet')
print 'table:=\n',table

print 'test'

你可能感兴趣的:(python 操作Excel 学习笔记)