如何利用pandas 将excel文件与csv文件进行相互转化
1.excel to csv
方法1:
import xlrd
import csv
def csv_from_excel():
wb = xlrd.open_workbook('excel.xlsx')
sh = wb.sheet_by_name('Sheet1')
your_csv_file = open('your_csv_file.csv', 'w')
wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
for rownum in range(sh.nrows):
wr.writerow(sh.row_values(rownum))
your_csv_file.close()
# runs the csv_from_excel function:
csv_from_excel()
方法 2:
import pandas as pd
def xlsx_to_csv_pd():
data_xls = pd.read_excel('1.xlsx', index_col=0,sheet_name='sheet1')
data_xls.to_csv('1.csv', encoding='utf-8')
if __name__ == '__main__':
xlsx_to_csv_pd()
2.csv to excel
方法1:
import os
import glob
import csv
from xlsxwriter.workbook import Workbook
for csvfile in glob.glob(os.path.join('.', '*.csv')):
workbook = Workbook(csvfile[:-4] + '.xlsx')
worksheet = workbook.add_worksheet()
with open(csvfile, 'rt', encoding='utf8') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet.write(r, c, col)
workbook.close()
方法2:
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()