问题
I'm Using Python 2.7.3 How can i convert excel file(.xls) to txt/.csv file
import matplotlib.pyplot as plt
x = []
y = []
t = []
fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#31312e')
readFile = open('data.csv', 'r')
sepFile = readFile.read().split('\n')
readFile.close()
for idx, plotPair in enumerate(sepFile):
if plotPair in '. ':
# skip. or space
continue
if idx > 1: # to skip the first line
xAndY = plotPair.split(',')
time_string = xAndY[0]
t.append(time_string)
y.append(float(xAndY[1]))
ax1 = fig.add_subplot(1, 1, 1, axisbg='blue')
ax1.plot(t, y, 'c', linewidth=3.3)
plt.title('IRRADIANCE')
plt.xlabel('TIME')
plt.show()
sample of my txt file:
TimeStamp,Irradiance 21/7/2014 0:00,0.66 21/7/2014 0:00,0.71 21/7/2014 0:00,0.65 21/7/2014 0:00,0.67 21/7/2014 0:01,0.58
回答1:
Use the xlrd and csv modules to convert xls to csv.
import xlrd
import csv
def xls_to_csv():
x = xlrd.open_workbook('data.xls')
x1 = x.sheet_by_name('Sheet1')
csvfile = open('data.csv', 'wb')
writecsv = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
for rownum in xrange(x1.nrows): #To determine the total rows.
writecsv.writerow(x1.row_values(rownum))
csvfile.close()
回答2:
If you are on a windows box or can access a windows box over the network the best solution maybe to write a Python script that uses the subprocess module to launches a vbscript that uses excel to export the file as a CSV file.
def doc_count(self, path_and_file):
print("---- doc_count ----")
pprint(path_and_file)
cmd = "cscript.exe word_count.vbs \"" + path_and_file + "\" //NoLogo"
print(cmd)
result = subprocess.check_output( cmd, shell=True )
print(result)
The code above is what I use to launch a vbs script to get line and word counts out of MS Word something similar should be possible with excel.
来源:https://stackoverflow.com/questions/24969274/converting-xls-file-into-csv-txt-file-in-python