Python編程快速上手——Excel到CSV的轉換程序案例分析
本文實例講述了Python Excel到CSV的轉換程序。分享給大家供大家參考,具體如下:
題目如下:
利用第十二章的openpyxl模塊,編程讀取當前工作目錄中的所有Excel文件,并輸出為csv文件。 一個Excel文件可能包含多個工作表,必須為每個表創建一個CSV文件。CSV文件的文件名應該是<Excel 文件名>_<表標題>.csv,其中< Excel 文件名 >是沒有拓展名的Excel文件名,<表標題>是Worksheet對象的title變量中的字符串 該程序包含許多嵌套的for循環。該程序框架看起來像這樣: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,將這些電子表格壓縮到程序所在目錄中。可以使用這些文件來測試程序
思路如下:
基本上按照題目給定的框架進行代碼的編寫 對英文進行翻譯,理解意思即可快速編寫出程序代碼如下:
#! python3import os, openpyxl, csvfor excelFile in os.listdir(’.CSV’): #我將解壓后的excel文件放入此文件夾 # 篩選出excel文件,創建工作表對象 if excelFile.endswith(’.xlsx’): wb = openpyxl.load_workbook(’.CSV’+ excelFile) for sheetName in wb.get_sheet_names(): #依次遍歷工作簿中的工作表 sheet = wb.get_sheet_by_name(sheetName) #根據excel文件名和工作表名創建csv文件名 #通過csv.writer創建csv file對象 basename = excelFile[0:-5] #將excel文件名進行切割,去掉文件名后綴.xlsx File = open(’{0}_{1}.csv’.format(basename,sheetName),’w’) #新建csv file對象 csvFile = csv.writer(File) #創建writer對象 #csvFileWriter.writerow() #遍歷表中每行 for rowNum in range(1,sheet.max_row+1):rowData = [] #防止每個單元格內容的列表#遍歷每行中的單元格for colNum in range(1,sheet.max_column + 1): #將每個單元格數據添加到rowData rowData.append(sheet.cell(row = rowNum,column = colNum).value)csvFile.writerow(rowData)#將rowData列表寫入到csv file File.close()
運行結果:
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python操作Excel表格技巧總結》、《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章: