回覆列表
  • 1 # 橘生淮南稻花薄荷微

    一、讀excel表

    讀excel要用到xlrd模組,官網安裝(http://pypi.python.org/pypi/xlrd)。然後就可以跟著裡面的例子稍微試一下就知道怎麼用了。大概的流程是這樣的:

    1、匯入模組

    複製程式碼程式碼如下:

    importxlrd

    2、開啟Excel檔案讀取資料

    複製程式碼程式碼如下:

    data=xlrd.open_workbook("excel.xls")

    3、獲取一個工作表

    ①table=data.sheets()[0]#透過索引順序獲取

    ②table=data.sheet_by_index(0)#透過索引順序獲取

    4、獲取整行和整列的值(返回陣列)

    複製程式碼程式碼如下:

    table.row_values(i)

    table.col_values(i)

    5、獲取行數和列數 

    複製程式碼程式碼如下:

    table.nrows

    table.ncols

    6、獲取單元格

    複製程式碼程式碼如下:

    table.cell(0,0).value

    table.cell(2,3).value

    就我自己使用的時候覺得還是獲取cell最有用,這就相當於是給了你一個二維陣列,餘下你就可以想怎麼幹就怎麼幹了。得益於這個十分好用的庫程式碼很是簡潔。但是還是有若干坑的存在導致話了一定時間探索。現在列出來供後人參考吧:

    1、首先就是我的統計是根據姓名統計各個表中的資訊的,但是除錯發現不同的表中各個名字貌似不能夠匹配,開始懷疑過編碼問題,不過後來發現是因為  空格。因為在excel中輸入的時候很可能會順手在一些名字後面加上幾個空格或是tab鍵,這樣看起來沒什麼差別,但是程式處理的時候這就是兩個完全  不同的串了。我的解決方法是給每個獲取的字串都加上strip()處理一下。效果良好

    2、還是字串的匹配,在判斷某個單元格中的字串(中文)是否等於我所給出的的時候發現無法匹配,並且各種unicode也不太奏效,百度過一些解決  方案,但是都比較複雜或是沒用。最後我採用了一個比較變通的方式:直接從excel中獲取我想要的值再進行比較,效果是不錯就是通用行不太好,個  呢不能問題還沒解決。

    二、寫excel表

    寫excel表要用到xlwt模組,官網下載(http://pypi.python.org/pypi/xlwt)。大致使用流程如下:

    1、匯入模組

    複製程式碼程式碼如下:

    importxlwt

    2、建立workbook(其實就是excel,後來儲存一下就行)

    複製程式碼程式碼如下:

    workbook=xlwt.Workbook(encoding="ascii")

    3、建立表

    複製程式碼程式碼如下:

    worksheet=workbook.add_sheet("MyWorksheet")

    4、往單元格內寫入內容

    複製程式碼程式碼如下:

    worksheet.write(0,0,label="Row0,Column0Value")

    5、儲存

    複製程式碼程式碼如下:

    workbook.save("Excel_Workbook.xls")

    由於我的需求比較簡單,所以這上面沒遇到什麼問題,唯一的就是建議還是用ascii編碼,不然可能會有一些詭異的現象。

    當然xlwt功能遠遠不止這些,他甚至可以設定各種樣式之類的。附上一點例子

    複製程式碼程式碼如下:

    ExamplesGeneratingExcelDocumentsUsingPython"sxlwt

    HerearesomesimpleexamplesusingPython"sxlwtlibrarytodynamicallygenerateExceldocuments.

    Pleasenoteausefulalternativemaybeezodf,whichallowsyoutogenerateODS(OpenDocumentSpreadsheet)filesforLibreOffice/OpenOffice.Youcancheckthemoutat:http://packages.python.org/ezodf/index.html

    TheSimplestExample

    importxlwt

    workbook=xlwt.Workbook(encoding="ascii")

    worksheet=workbook.add_sheet("MyWorksheet")

    worksheet.write(0,0,label="Row0,Column0Value")

    workbook.save("Excel_Workbook.xls")

    FormattingtheContentsofaCell

    importxlwt

    workbook=xlwt.Workbook(encoding="ascii")

    worksheet=workbook.add_sheet("MyWorksheet")

    font=xlwt.Font()#CreatetheFont

    font.name="TimesNewRoman"

    font.bold=True

    font.underline=True

    font.italic=True

    style=xlwt.XFStyle()#CreatetheStyle

    style.font=font#ApplytheFonttotheStyle

    worksheet.write(0,0,label="Unformattedvalue")

    worksheet.write(1,0,label="Formattedvalue",style)#ApplytheStyletotheCell

    workbook.save("Excel_Workbook.xls")

    AttributesoftheFontObject

    font.bold=True#Maybe:True,False

    font.italic=True#Maybe:True,False

    font.struck_out=True#Maybe:True,False

    font.underline=xlwt.Font.UNDERLINE_SINGLE#Maybe:UNDERLINE_NONE,UNDERLINE_SINGLE,UNDERLINE_SINGLE_ACC,UNDERLINE_DOUBLE,UNDERLINE_DOUBLE_ACC

    font.escapement=xlwt.Font.ESCAPEMENT_SUPERSCRIPT#Maybe:ESCAPEMENT_NONE,ESCAPEMENT_SUPERSCRIPT,ESCAPEMENT_SUBSCRIPT

    font.family=xlwt.Font.FAMILY_ROMAN#Maybe:FAMILY_NONE,FAMILY_ROMAN,FAMILY_SWISS,FAMILY_MODERN,FAMILY_SCRIPT,FAMILY_DECORATIVE

    font.charset=xlwt.Font.CHARSET_ANSI_LATIN#Maybe:CHARSET_ANSI_LATIN,CHARSET_SYS_DEFAULT,CHARSET_SYMBOL,CHARSET_APPLE_ROMAN,CHARSET_ANSI_JAP_SHIFT_JIS,CHARSET_ANSI_KOR_HANGUL,CHARSET_ANSI_KOR_JOHAB,CHARSET_ANSI_CHINESE_GBK,CHARSET_ANSI_CHINESE_BIG5,CHARSET_ANSI_GREEK,CHARSET_ANSI_TURKISH,CHARSET_ANSI_VIETNAMESE,CHARSET_ANSI_HEBREW,CHARSET_ANSI_ARABIC,CHARSET_ANSI_BALTIC,CHARSET_ANSI_CYRILLIC,CHARSET_ANSI_THAI,CHARSET_ANSI_LATIN_II,CHARSET_OEM_LATIN_I

    font.colour_index=?

    font.get_biff_record=?

    font.height=0x00C8#C8inHex(indecimal)=10pointsinheight.

    font.name=?

    font.outline=?

    font.shadow=?

    SettingtheWidthofaCell

    importxltw

    workbook=xlwt.Workbook()

    worksheet=workbook.add_sheet("MySheet")

    worksheet.write(0,0,"MyCellContents")

    worksheet.col(0).width=3333#3333=1"(oneinch).

    workbook.save("Excel_Workbook.xls")

    EnteringaDateintoaCell

    importxlwt

    importdatetime

    workbook=xlwt.Workbook()

    worksheet=workbook.add_sheet("MySheet")

    style=xlwt.XFStyle()

    style.num_format_str="M/D/YY"#Otheroptions:D-MMM-YY,D-MMM,MMM-YY,h:mm,h:mm:ss,h:mm,h:mm:ss,M/D/YYh:mm,mm:ss,[h]:mm:ss,mm:ss.0

    worksheet.write(0,0,datetime.datetime.now(),style)

    workbook.save("Excel_Workbook.xls")

    AddingaFormulatoaCell

    importxlwt

    workbook=xlwt.Workbook()

    worksheet=workbook.add_sheet("MySheet")

    worksheet.write(0,0,5)#Outputs5

    worksheet.write(0,1,2)#Outputs2

    worksheet.write(1,0,xlwt.Formula("A1*B1"))#Shouldoutput"10"(A1[5]*A2[2])

    worksheet.write(1,1,xlwt.Formula("SUM(A1,B1)"))#Shouldoutput"7"(A1[5]+A2[2])

    workbook.save("Excel_Workbook.xls")

    AddingaHyperlinktoaCell

    importxlwt

    workbook=xlwt.Workbook()

    worksheet=workbook.add_sheet("MySheet")

    worksheet.write(0,0,xlwt.Formula("HYPERLINK("http://www.google.com";"Google")"))#Outputsthetext"Google"linkingtohttp://www.google.com

    workbook.save("Excel_Workbook.xls")

    MergingColumnsandRows

    importxlwt

    workbook=xlwt.Workbook()

    worksheet=workbook.add_sheet("MySheet")

    worksheet.write_merge(0,0,0,3,"FirstMerge")#Mergesrow0"scolumns0through3.

    font=xlwt.Font()#CreateFont

    font.bold=True#SetfonttoBold

    style=xlwt.XFStyle()#CreateStyle

    style.font=font#AddBoldFonttoStyle

    worksheet.write_merge(1,2,0,3,"SecondMerge",style)#Mergesrow1through2"scolumns0through3.

    workbook.save("Excel_Workbook.xls")

    SettingtheAlignmentfortheContentsofaCell

    importxlwt

    workbook=xlwt.Workbook()

    worksheet=workbook.add_sheet("MySheet")

    alignment=xlwt.Alignment()#CreateAlignment

    alignment.horz=xlwt.Alignment.HORZ_CENTER#Maybe:HORZ_GENERAL,HORZ_LEFT,HORZ_CENTER,HORZ_RIGHT,HORZ_FILLED,HORZ_JUSTIFIED,HORZ_CENTER_ACROSS_SEL,HORZ_DISTRIBUTED

    alignment.vert=xlwt.Alignment.VERT_CENTER#Maybe:VERT_TOP,VERT_CENTER,VERT_BOTTOM,VERT_JUSTIFIED,VERT_DISTRIBUTED

    style=xlwt.XFStyle()#CreateStyle

    style.alignment=alignment#AddAlignmenttoStyle

    worksheet.write(0,0,"CellContents",style)

    workbook.save("Excel_Workbook.xls")

    AddingBorderstoaCell

    #Pleasenote:WhileIwasabletofindtheseconstantswithinthesourcecode,onmysystem(usingLibreOffice,)Iwasonlypresentedwithasolidline,varyingfromthintothick;nodottedordashedlines.

    importxlwt

    workbook=xlwt.Workbook()

    worksheet=workbook.add_sheet("MySheet")

    borders=xlwt.Borders()#CreateBorders

    borders.left=xlwt.Borders.DASHED#Maybe:NO_LINE,THIN,MEDIUM,DASHED,DOTTED,THICK,DOUBLE,HAIR,MEDIUM_DASHED,THIN_DASH_DOTTED,MEDIUM_DASH_DOTTED,THIN_DASH_DOT_DOTTED,MEDIUM_DASH_DOT_DOTTED,SLANTED_MEDIUM_DASH_DOTTED,or0x00through0x0D.

    borders.right=xlwt.Borders.DASHED

    borders.top=xlwt.Borders.DASHED

    borders.bottom=xlwt.Borders.DASHED

    borders.left_colour=0x40

    borders.right_colour=0x40

    borders.top_colour=0x40

    borders.bottom_colour=0x40

    style=xlwt.XFStyle()#CreateStyle

    style.borders=borders#AddBorderstoStyle

    worksheet.write(0,0,"CellContents",style)

    workbook.save("Excel_Workbook.xls")

    SettingtheBackgroundColorofaCell

    importxlwt

    workbook=xlwt.Workbook()

    worksheet=workbook.add_sheet("MySheet")

    pattern=xlwt.Pattern()#CreatethePattern

    pattern.pattern=xlwt.Pattern.SOLID_PATTERN#Maybe:NO_PATTERN,SOLID_PATTERN,or0x00through0x12

    pattern.pattern_fore_colour=5#Maybe:8through63.0=Black,1=White,2=Red,3=Green,4=Blue,5=Yellow,6=Magenta,7=Cyan,16=Maroon,17=DarkGreen,18=DarkBlue,19=DarkYellow,almostbrown),20=DarkMagenta,21=Teal,22=LightGray,23=DarkGray,thelistgoeson...

    style=xlwt.XFStyle()#CreatethePattern

    style.pattern=pattern#AddPatterntoStyle

    worksheet.write(0,0,"CellContents",style)

    workbook.save("Excel_Workbook.xls")

    TODO:ThingsLefttoDocument

    -Panes--separateviewswhicharealwaysinview

    -BorderColors(documentedabove,butnottakingeffectasitshould)

    -BorderWidths(documentabove,butnotworkingasexpected)

    -Protection

    -RowStyles

    -Zoom/Manification

    -WSProps?

    SourceCodeforreferenceavailableat:https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/

  • 中秋節和大豐收的關聯?
  • 馬伊琍與文章離婚透露出什麼?