#方法一:複製生成一個新表,可以寫入單元格,儲存為.xls檔案
import xlrd
from xlutils.copy import copy
oldWb = xlrd.open_workbook("d:/1.xlsx")#先開啟已存在的表
newWb = copy(oldWb)#複製
newWs = newWb.get_sheet(0)#取sheet表
newWs.write(2, 4, "pass")#寫入 2行4列寫入pass
newWb.save("d:/2.xls")
#方法二:在記憶體中建立一個新表,寫入單元格,儲存為.xls新檔案
import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet('Sheet1')
sheet.write(0,0,'hello')
sheet.write(1,0,'你好')
book.save('d:\hello.xls')
# 方法三: 以現有檔案為模板,建立副本,修改單元格內容
import xlrd
from xlutils.copy import copy
book = xlrd.open_workbook('fruit.xlsx')
sheet = book.sheet_by_index(0)
newWb = copy(book)
newWs = newWb.get_sheet(0)#取sheet表
newWs.write(2, 4, "pass")#寫入 2行4列寫入pass
newWb.save("new.xls")
# 方法四:由列表型別資料建立新的excel檔案
import xlwt
proj = ['名稱','單價/元','庫存/kg']
fruit = ['蘋果','梨','香蕉','橘子']
price = [8,3.5,4.5,3.8]
storage = [150,130,100,300]
book = xlwt.Workbook()
sheet = book.add_sheet('Sheet1')
for i in range(0,len(proj)):
sheet.write(0,i,proj[i]) #按行插入行標題
for i in range(0,len(fruit)):
sheet.write(i+1,0,fruit[i]) #插入第一列水果名稱
for i in range(0,len(price)):
sheet.write(i+1,1,price[i]) #插入第二列單價
for i in range(0,len(storage)):
sheet.write(i+1,2,storage[i]) #插入第三列庫存
book.save('fruit2.xls')
# 方法五新建.xlsx檔案
import openpyxl
book = openpyxl.Workbook()
sheet = book.create_sheet('Sheet1',0)
proj = ['名稱','單價/元','庫存/kg']
fruit = ['蘋果','香蕉','梨','橘子']
price = [8,3.5,4.5,3.8]
storage = [150,130,300,100]
for i in range(len(proj)):
sheet.cell(1,i+1,proj[i])
for i in range(len(fruit)):
sheet.cell(i+2,1,fruit[i])
for i in range(len(price)):
sheet.cell(i+2,2,price[i])
for i in range(len(storage)):
sheet.cell(i+2,3,storage[i])
book.save('fruit2.xlsx')
rows = sheet.max_row
sheet.insert_rows(rows+2)
cherry = ['櫻桃',17,80]
for j in cherry:
sheet.cell(rows+1,cherry.index(j)+1,j) #向單元格寫入內容j
book.save('fruit2.xlsx')
#修改單元格內容
sheet.cell(3,2,4)
sheet['B3'] = 5
book.save('fruit2.xlsx')
#追加行內容
straberry = ['草莓',20,50]
sheet.append(straberry)
book.save('fruit2.xlsx')