Python編程快速上手——Excel到CSV的轉(zhuǎn)換程序案例分析
本文實例講述了Python Excel到CSV的轉(zhuǎn)換程序。分享給大家供大家參考,具體如下:
題目如下:
利用第十二章的openpyxl模塊,編程讀取當(dāng)前工作目錄中的所有Excel文件,并輸出為csv文件。 一個Excel文件可能包含多個工作表,必須為每個表創(chuàng)建一個CSV文件。CSV文件的文件名應(yīng)該是<Excel 文件名>_<表標(biāo)題>.csv,其中< Excel 文件名 >是沒有拓展名的Excel文件名,<表標(biāo)題>是Worksheet對象的title變量中的字符串 該程序包含許多嵌套的for循環(huán)。該程序框架看起來像這樣:for excelFile in os.listdir(’.’): # skip non-xlsx files, load the workbook object for sheetname in wb.get_sheet_names(): #Loop through every sheet in the workbook sheet = wb.get_sheet_by_name(sheetname) # create the csv filename from the Excel filename and sheet title # create the csv.writer object for this csv file #loop through every row in the sheet for rowNum in range(1, sheet.max_row + 1): rowData = [] #append each cell to this list # loop through each cell in the row for colNum in range (1, sheet.max_column + 1): #Append each cell’s data to rowData # write the rowData list to CSV file csvFile.close()
從htttp://nostarch.com/automatestuff/下載zip文件excelSpreadseets.zip,將這些電子表格壓縮到程序所在目錄中??梢允褂眠@些文件來測試程序
思路如下:
基本上按照題目給定的框架進(jìn)行代碼的編寫 對英文進(jìn)行翻譯,理解意思即可快速編寫出程序代碼如下:
#! python3import os, openpyxl, csvfor excelFile in os.listdir(’.CSV’): #我將解壓后的excel文件放入此文件夾 # 篩選出excel文件,創(chuàng)建工作表對象 if excelFile.endswith(’.xlsx’): wb = openpyxl.load_workbook(’.CSV’+ excelFile) for sheetName in wb.get_sheet_names(): #依次遍歷工作簿中的工作表 sheet = wb.get_sheet_by_name(sheetName) #根據(jù)excel文件名和工作表名創(chuàng)建csv文件名 #通過csv.writer創(chuàng)建csv file對象 basename = excelFile[0:-5] #將excel文件名進(jìn)行切割,去掉文件名后綴.xlsx File = open(’{0}_{1}.csv’.format(basename,sheetName),’w’) #新建csv file對象 csvFile = csv.writer(File) #創(chuàng)建writer對象 #csvFileWriter.writerow() #遍歷表中每行 for rowNum in range(1,sheet.max_row+1):rowData = [] #防止每個單元格內(nèi)容的列表#遍歷每行中的單元格for colNum in range(1,sheet.max_column + 1): #將每個單元格數(shù)據(jù)添加到rowData rowData.append(sheet.cell(row = rowNum,column = colNum).value)csvFile.writerow(rowData)#將rowData列表寫入到csv file File.close()
運行結(jié)果:
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python操作Excel表格技巧總結(jié)》、《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章:
1. ASP基礎(chǔ)入門第四篇(腳本變量、函數(shù)、過程和條件語句)2. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)3. jscript與vbscript 操作XML元素屬性的代碼4. jsp 實現(xiàn)的簡易mvc模式示例5. JSP開發(fā)之hibernate之單向多對一關(guān)聯(lián)的實例6. HTML5實戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)7. 基于PHP做個圖片防盜鏈8. Jsp servlet驗證碼工具類分享9. XML在語音合成中的應(yīng)用10. php使用正則驗證密碼字段的復(fù)雜強度原理詳細(xì)講解 原創(chuàng)
