Python編程快速上手——Excel到CSV的轉(zhuǎn)換程序案例分析
本文實(shí)例講述了Python Excel到CSV的轉(zhuǎn)換程序。分享給大家供大家參考,具體如下:
題目如下:
利用第十二章的openpyxl模塊,編程讀取當(dāng)前工作目錄中的所有Excel文件,并輸出為csv文件。 一個(gè)Excel文件可能包含多個(gè)工作表,必須為每個(gè)表創(chuàng)建一個(gè)CSV文件。CSV文件的文件名應(yīng)該是<Excel 文件名>_<表標(biāo)題>.csv,其中< Excel 文件名 >是沒(méi)有拓展名的Excel文件名,<表標(biāo)題>是Worksheet對(duì)象的title變量中的字符串 該程序包含許多嵌套的for循環(huán)。該程序框架看起來(lái)像這樣: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,將這些電子表格壓縮到程序所在目錄中。可以使用這些文件來(lái)測(cè)試程序
思路如下:
基本上按照題目給定的框架進(jìn)行代碼的編寫(xiě) 對(duì)英文進(jìn)行翻譯,理解意思即可快速編寫(xiě)出程序代碼如下:
#! python3import os, openpyxl, csvfor excelFile in os.listdir(’.CSV’): #我將解壓后的excel文件放入此文件夾 # 篩選出excel文件,創(chuàng)建工作表對(duì)象 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文件名 #通過(guò)csv.writer創(chuàng)建csv file對(duì)象 basename = excelFile[0:-5] #將excel文件名進(jìn)行切割,去掉文件名后綴.xlsx File = open(’{0}_{1}.csv’.format(basename,sheetName),’w’) #新建csv file對(duì)象 csvFile = csv.writer(File) #創(chuàng)建writer對(duì)象 #csvFileWriter.writerow() #遍歷表中每行 for rowNum in range(1,sheet.max_row+1):rowData = [] #防止每個(gè)單元格內(nèi)容的列表#遍歷每行中的單元格for colNum in range(1,sheet.max_column + 1): #將每個(gè)單元格數(shù)據(jù)添加到rowData rowData.append(sheet.cell(row = rowNum,column = colNum).value)csvFile.writerow(rowData)#將rowData列表寫(xiě)入到csv file File.close()
運(yùn)行結(jié)果:
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Python操作Excel表格技巧總結(jié)》、《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門(mén)與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. python爬蟲(chóng)beautifulsoup解析html方法2. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以?xún)?nèi))3. python 實(shí)現(xiàn)aes256加密4. 詳解Python模塊化編程與裝飾器5. css進(jìn)階學(xué)習(xí) 選擇符6. Python性能測(cè)試工具Locust安裝及使用7. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式8. 使用Python解析Chrome瀏覽器書(shū)簽的示例9. html小技巧之td,div標(biāo)簽里內(nèi)容不換行10. python web框架的總結(jié)
