如何在Python中將Excel轉換為CSV
在本文中,我們將向您展示如何使用Python將Excel檔案轉換為CSV檔案(逗號分隔值)。
假設我們有一個名為sampleTutorialsPoint.xlsx的Excel檔案,其中包含一些隨機文字。我們將轉換該Excel檔案並返回一個CSV檔案。
sampleTutorialsPoint.xlsx
球員姓名 | 年齡 | 型別 | 國家 | 球隊 | 得分 | 得分 |
---|---|---|---|---|---|---|
Virat Kohli | 33 | 擊球手 | 印度 | 皇家挑戰者班加羅爾 | 6300 | 20 |
Bhuvaneshwar Kumar | 34 | 擊球手 | 印度 | 太陽昇起海德拉巴 | 333 | 140 |
Mahendra Singh Dhoni | 39 | 擊球手 | 印度 | 欽奈超級國王 | 4500 | 0 |
Rashid Khan | 28 | 投球手 | 阿富汗 | 古吉拉特巨人 | 500 | 130 |
Hardik Pandya | 29 | 全能型選手 | 印度 | 古吉拉特巨人 | 2400 | 85 |
David Warner | 34 | 擊球手 | 澳大利亞 | 德里首都 | 5500 | 12 |
Kieron Pollard | 35 | 全能型選手 | 西印度群島 | 孟買印第安人 | 3000 | 67 |
Rohit Sharma | 33 | 擊球手 | 印度 | 孟買印第安人 | 5456 | 20 |
Kane Williamson | 33 | 擊球手 | 紐西蘭 | 太陽昇起海德拉巴 | 3222 | 5 |
Kagiso Rabada | 29 | 投球手 | 南非 | 勒克瑙首都 | 335 | 111 |
方法一:使用Pandas模組將Excel轉換為CSV
演算法(步驟)
以下是執行所需任務的演算法/步驟:
匯入pandas模組(Pandas是一個Python開源資料處理和分析包)
建立一個變數來儲存輸入Excel檔案的路徑。
使用pandas read_excel() 函式讀取給定的Excel檔案內容(將Excel檔案物件讀取到資料框物件中)。
使用to_csv() 函式將Excel檔案轉換為CSV檔案(將物件轉換為CSV檔案),並將輸出Excel檔名、index設定為None,header設定為true作為引數。
使用read_csv() 函式讀取輸出CSV檔案(將CSV檔案載入為pandas資料框),並使用pandas模組的DataFrame()函式將其轉換為資料框物件。
顯示/顯示資料框物件。
示例
以下程式將Excel檔案轉換為CSV檔案並返回一個新的CSV檔案
# importing pandas module import pandas as pd # input excel file path inputExcelFile ="sampleTutorialsPoint.xlsx" # Reading an excel file excelFile = pd.read_excel (inputExcelFile) # Converting excel file into CSV file excelFile.to_csv ("ResultCsvFile.csv", index = None, header=True) # Reading and Converting the output csv file into a dataframe object dataframeObject = pd.DataFrame(pd.read_csv("ResultCsvFile.csv")) # Displaying the dataframe object dataframeObject
輸出
執行上述程式將生成以下輸出:
| index | Player Name | Age | Type | Country | Team |Runs | Wickets | |--------|---------------------|-----|-----------|------------------|---------------------------|----- |---------| | 0 |Virat Kohli | 33|Batsman | India |Royal Challengers Bangalore| 6300 | 20 | | 1 |Bhuvaneshwar Kumar | 34|Batsman | India |Sun Risers Hyderabad | 333 | 140 | | 2 |Mahendra Singh Dhoni | 39|Batsman | India |Chennai Super Kings | 4500 | 0 | | 3 |Rashid Khan | 28|Bowler | Afghanistan |Gujarat Titans | 500 | 130 | | 4 |Hardik Pandya | 29|All rounder| India |Gujarat Titans | 2400 | 85 | | 5 |David Warner | 34|Batsman | Australia |Delhi Capitals | 5500 | 12 | | 6 |Kieron Pollard | 35|All rounder| West Indies |Mumbai Indians | 3000 | 67 | | 7 |Rohit Sharma | 33|Batsman | India |Mumbai Indians | 5456 | 20 | | 8 |Kane Williamson | 33|Batsman | New Zealand |Sun Risers Hyderabad | 3222 | 5 | | 9 |Kagiso Rabada | 29|Bowler | South Africa |Lucknow Capitals | 335 | 111 |
在這個程式中,我們使用pandas read_excel()函式讀取包含一些隨機虛擬資料的Excel檔案,然後使用to_csv()函式將Excel檔案轉換為csv。如果我們將index作為false引數傳遞,則最終的CSV檔案不會在開頭包含索引行。然後我們將CSV轉換為資料框,以檢視Excel檔案中的值是否已複製到CSV檔案中。
方法二:使用openpyxl和CSV模組將Excel轉換為CSV
演算法(步驟)
以下是執行所需任務的演算法/步驟:
使用import關鍵字匯入openpyxl(Openpyxl 是一個用於與Excel檔案互動和管理的Python包。支援Excel 2010及更高版本的檔案,副檔名為xlsx/xlsm/xltx/xltm。資料科學家使用Openpyxl進行資料分析、資料複製、資料探勘、繪製圖表、設定樣式表、新增公式以及其他操作)和CSV模組。
pip install openpyxl
建立一個變數來儲存輸入Excel檔案的路徑。
要建立/載入工作簿物件,請將輸入Excel檔案傳遞給openpyxl模組的load_workbook() 函式(載入工作簿)。
使用open() 和writer() 函式以寫入模式開啟輸出CSV檔案,以將輸入Excel檔案轉換為CSV檔案。
使用for迴圈遍歷工作表的每一行。
使用writerow() 函式將Excel檔案的單元格資料逐行寫入結果CSV檔案。
示例
以下程式將Excel檔案轉換為CSV檔案並返回一個新的CSV檔案:
# importing openpyxl module and csv modules import openpyxl import csv # input excel file path inputExcelFile = 'sampleTutorialsPoint.xlsx' # creating or loading an excel workbook newWorkbook = openpyxl.load_workbook(inputExcelFile) # getting the active workbook sheet(Bydefault-->Sheet1) firstWorksheet = newWorkbook.active # Opening a output csv file in write mode OutputCsvFile = csv.writer(open("ResultCsvFile.csv", 'w'), delimiter=",") # Traversing in each row of the worshsheet for eachrow in firstWorksheet.rows: # Writing data of the excel file into the result csv file row-by-row OutputCsvFile.writerow([cell.value for cell in eachrow])
輸出
執行上述程式將建立一個新的CSV檔案(ResultCsvFile.csv),其中包含Excel的資料。
在這個程式中,我們有一個包含一些隨機虛擬資料的Excel檔案,我們將其載入為openpyxl工作簿並使用active屬性進行設定。然後我們建立了一個新的CSV檔案並以寫入模式開啟它,然後我們逐行遍歷Excel檔案並將資料複製到新建立的CSV檔案中。
結論
在本教程中,我們學習瞭如何讀取Excel檔案並將其轉換為openpyxl工作簿,然後如何將其轉換為CSV檔案並刪除索引,最後如何將CSV檔案轉換為pandas資料框。