Python csv轉換爲excel學習筆記:python
openpyxl模塊須要安裝pip install openpyxl函數
import openpyxl import csv '''讀取csv文件寫入excel表格''' #建立工做簿對象 work_book = openpyxl.Workbook() #建立sheet work_sheet = work_book.create_sheet(title=u"cpu和內存") #打開csv文件,沒有異常捕獲,沒有定義成函數,作成模塊更好 csvfile = open('20170615.csv','rb') #獲取csv.reader lines = csv.reader(csvfile) #row row = 1 #sheet第一行,就叫他標題吧 title_list=[u'採集時間',u'主機',u'CPU使用率(%)',u'MEM使用率(%)'] #寫入第一行,標題 for i in range(1,title_len+1): work_sheet.cell(row = row, column = i).value = title_list[i-1] #從第二行開始寫入從csv讀取的內容 for line in lines: lin = 1 for i in line: work_sheet.cell(row = row +1, column = lin).value = i lin += 1 row += 1 #關閉文件 csvfile.close() #保存工做表 work_book.save('20170615_cpu.xlsx')
下面是一個Excel轉csv的代碼,網上借鑑,能夠直接做爲模塊使用:學習
# -*- coding: utf-8 -*- import xlrd import csv from os import sys def csv_from_excel(excel_file): workbook = xlrd.open_workbook(excel_file) all_worksheets = workbook.sheet_names() for worksheet_name in all_worksheets: worksheet = workbook.sheet_by_name(worksheet_name) your_csv_file = open(''.join([worksheet_name,'.csv']), 'wb') wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL) for rownum in xrange(worksheet.nrows): wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)]) your_csv_file.close() if __name__ == "__main__": csv_from_excel(sys.argv[1])