Python編程快速上手——Excel到CSV的轉(zhuǎn)換程序案例分析
本文實例講述了Python Excel到CSV的轉(zhuǎn)換程序。分享給大家供大家參考,具體如下:
題目如下:
- 利用第十二章的openpyxl模塊,編程讀取當前工作目錄中的所有Excel文件,并輸出為csv文件。
- 一個Excel文件可能包含多個工作表,必須為每個表創(chuàng)建一個CSV文件。CSV文件的文件名應該是<Excel 文件名>_<表標題>.csv,其中< Excel 文件名 >是沒有拓展名的Excel文件名,<表標題>是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,將這些電子表格壓縮到程序所在目錄中??梢允褂眠@些文件來測試程序
思路如下:
- 基本上按照題目給定的框架進行代碼的編寫
- 對英文進行翻譯,理解意思即可快速編寫出程序
代碼如下:
#! python3
import os, openpyxl, csv
for 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文件名進行切割,去掉文件名后綴.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īng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
解決python3在anaconda下安裝caffe失敗的問題
下面小編就為大家?guī)硪黄鉀Qpython3在anaconda下安裝caffe失敗的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06
Python線程池ThreadPoolExecutor使用方式
這篇文章主要介紹了Python線程池ThreadPoolExecutor使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
Pandas中DataFrame.head()函數(shù)的具體使用
DataFrame.head()是Pandas庫中一個非常重要的函數(shù),用于返回DataFrame對象的前n行,本文主要介紹了Pandas中DataFrame.head()函數(shù)的具體使用,感興趣的可以了解一下2024-07-07
Python調(diào)用VBA實現(xiàn)保留原始樣式的表格合并方法
本文主要介紹了Python調(diào)用VBA實現(xiàn)保留原始樣式的表格合并方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-01-01

