django操作excel

來源:互聯網
上載者:User

標籤:style   http   使用   io   檔案   資料   for   代碼   

python操作excel除了讀就是寫。

1 從讀開始 xlrd  :http://pypi.python.org/pypi/xlrd

匯入:import xlrd

開啟excel: file = xlrd.open_workbook(‘demo.xls‘)

查看檔案中包含sheet的名稱:file.sheet_names()

得到第一個工作表,或者通過索引順序 或 工作表名稱
sheet = file.sheets()[0]
sheet = file.sheet_by_index(0)
sheet = file.sheet_by_name(u‘Sheet1‘)

擷取行數和列數
nrows = sheet.nrows
ncols = sheet.ncols

迴圈行,得到索引的列表
for rownum in range(sheet.nrows):
    print sheet.row_values(rownum)

擷取整行和整列的值(數組)
sheet.row_values(i)
sheet.col_values(i)

儲存格(索引擷取)
cell_A1 = sheet.cell(0,0).value
cell_C4 = sheet.cell(2,3).value

分別使用行列索引
cell_A1 = sheet.row(0)[0].value
cell_A2 = sheet.col(1)[0].value

2 寫 xlwt :http://pypi.python.org/pypi/xlrd

匯入xlwt import xlwt

建立一個excel檔案

file = xlwt.Workbook() #注意這裡的Workbook首字母是大寫,無語吧

建立一個sheet

sheet = file.add_sheet(‘sheet name‘)

寫入資料sheet.write(行,列,value)

sheet.write(0,0,‘test‘)

如果對一個儲存格重複操作,會引發
returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u‘sheet 1‘ rowx=0 colx=0

所以在開啟時加cell_overwrite_ok=True解決

sheet = file.add_sheet(‘sheet name‘,cell_overwrite_ok=True)

儲存檔案

file.save(‘demo.xls‘)

另外,使用style

style = xlwt.XFStyle() #初始化樣式

font = xlwt.Font() #為樣式建立字型

font.name = ‘Times New Roman‘

font.bold = True

style.font = font #為樣式設定字型

sheet.write(0, 0, ‘some bold Times text‘, style) # 使用樣式

xlwt 允許儲存格或者整行地設定格式。還可以添加連結以及公式。

原始碼中的模組:

  dates.py, 展示如何設定不同的資料格式

  hyperlinks.py, 展示如何建立超連結  

  merged.py, 展示如何合并格子

  row_styles.py, 展示如何應用Style到整行格子中.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.