python 簡單解析excel檔案

2021-06-27 03:02:58 字數 2020 閱讀 1804

目前的公司的專案需要將策劃給的excel檔案弄成xml格式。上網搜了下,感覺用python 寫個指令碼轉換比較方便。第一步學習下看python是如何解析excel的。首先需要安裝python和第三方庫xlrd。不多說了,自己使用的python是2.6版本。在windows下解析。

簡單說下解析的大致步驟:

1. 引入xlrd包,呼叫他的open_workbook方法開啟excel檔案讀取裡面的資料,這個方法引數很多,主要是第乙個,傳入要解析的excel檔案。

data = xlrd.open_workbook("自己的excel路徑")

2.然後需要獲取excel中的某個工作表,xlrd提供了三種方法:

table = data.sheets()[index] index就是就是左下角的工作表的索引順序,從0開始。

table = data.sheet_by_index(index) 看下他們的實現發現這個和上面的其實一樣的,只是上一種是data.sheets()或獲取此excel中的所有表,生成乙個list,再通過列表的下標取到我們需要的表。

table = data.sheet_by_name(u'sheet_name'),這個是通過表的名稱來獲取的

3.可以通過table.nrows來獲取表的行數,table.ncols來獲取表的列數

4.這樣可以獲取到整行的資料 talbe.row_values(index) ,index就是要獲取的所在行數,返回的是乙個list列表儲存資料。通用的道理,table.col_values(index),就是index列的資料。返回list。

5.獲取單元格的資料。通過table.cell(row_index, col_index)可以得到excel中row_index行col_index列的資料,這樣得到的其實是這樣的資料:型別: 欄位名(unicode編碼),我們這裡使用的是utf-8編碼,比如我們這個excel表中的第一行第一列的table.cell(0, 0)得到的就是:text:u'itemid'。要是獲取值就使用table.cell(row_index, col_index).value即可。

由於我們這裡只是簡單的解析出已經存在的excel表,所以非常簡單。寫了非常簡單的列子,將解析的資料列印出來。先看看excel檔案內容

再看看**:

#! encoding=utf-8

import xlrd

def open_excel(file):

try:

data = xlrd.open_workbook(file)

return data

except exception, e:

print str(e)

def excel_table_byindex(file, colnnameindex=0, by_index=0):

data = open_excel(file)

table = data.sheets()[by_index]

#行數nrows = table.nrows

#列數ncols = table.ncols

#列印出每個單元格的資料

for nrow in range(0, nrows):

#rownames = table.row_values(nrow)

#print rownames

for ncol in range(0, ncols):

#colnames = table.col_values(ncol)

#print colnames

print table.cell(nrow, ncol).value

if __name__ == "__main__":

excel_table_byindex('d:\daoju.xlsx')

**是非常簡單的,由於結果 很多,只是擷取了一部分看看

Excel解析入庫

1.配置資料庫連線字串 1 sqlserver資料庫連線 2 oracle資料庫連線 2.獲取資料庫連線字串 sqlserver sql.cs private static string connstr configurationmanager.connectionstrings sql conne...

上傳解析Excel

專案中上傳解析excel的功能,非常普遍,因為方便,接下來就寫乙個工具類對excel進行解析 引入poi 阿帕奇依賴 工具類的書寫public class excelutils else if excel 2007 suffix.equalsignorecase suffixname catch i...

解析Excel資料

解析excel資料常用的方式就是使用poi和jxl工具了,這兩種工具使用起來有些類似,這裡記錄一下使用方式提供個參考 file file new file filepath fileinputstream fis new fileinputstream file workbook workbookf...