Python之xlsx檔案與csv檔案相互轉換

來源:互聯網
上載者:User

標籤:int   code   str   __name__   def   enc   sheet   div   imp   

1 xlsx檔案轉csv檔案
import xlrdimport csv def xlsx_to_csv():    workbook = xlrd.open_workbook(‘1.xlsx‘)    table = workbook.sheet_by_index(0)    with codecs.open(‘1.csv‘, ‘w‘, encoding=‘utf-8‘) as f:        write = csv.writer(f)        for row_num in range(table.nrows):            row_value = table.row_values(row_num)            write.writerow(row_value) if __name__ == ‘__main__‘:    xlsx_to_csv()

2 使用第三方庫pandas將xlsx檔案轉csv檔案

import pandas as pd  def xlsx_to_csv_pd():    data_xls = pd.read_excel(‘1.xlsx‘, index_col=0)    data_xls.to_csv(‘1.csv‘, encoding=‘utf-8‘)  if __name__ == ‘__main__‘:    xlsx_to_csv_pd()

3 csv檔案轉換成xlsx檔案

import csvimport xlwt def csv_to_xlsx():    with open(‘1.csv‘, ‘r‘, encoding=‘utf-8‘) as f:        read = csv.reader(f)        workbook = xlwt.Workbook()        sheet = workbook.add_sheet(‘data‘)  # 建立一個sheet表格        l = 0        for line in read:            print(line)            r = 0            for i in line:                print(i)                sheet.write(l, r, i)  # 一個一個將儲存格資料寫入                r = r + 1            l = l + 1         workbook.save(‘1.xlsx‘)  # 儲存Excel   if __name__ == ‘__main__‘:    csv_to_xlsx()
4 使用pandas將csv檔案轉成xlsx檔案
import pandas as pd def csv_to_xlsx_pd():    csv = pd.read_csv(‘1.csv‘, encoding=‘utf-8‘)    csv.to_excel(‘1.xlsx‘, sheet_name=‘data‘)  if __name__ == ‘__main__‘:    csv_to_xlsx_pd()

 

Python之xlsx檔案與csv檔案相互轉換

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.