通过Ajax调用python脚本写入Excel

时间:2013-07-01 15:14:29

标签: python ajax django xlsxwriter

我正在使用Django Web应用程序,我正在尝试通过Ajax自动导出一些数据到excel。现在,我的一个模板中有一个按钮,当用户单击它时,它会绑定到Ajax函数调用。该Ajax函数调用我编写的python脚本,该脚本使用xlsxwriter python库写出excel。该脚本在我的机器上本地工作,但不会在Web应用程序上保存任何内容。

这是我的ajax.py文件中的函数:

from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
from hipercic.apps.NeuroCiC import models
from django.core.files import storage
import file_analysis
import sys

@dajaxice_register
def export_excel_file(request, id):
  print 'TRIAL ID', id

  try:
    trial = models.Trial.objects.get(pk=id)
  except:
    'Could not find trial'
  else:
    print 'Found trial'
    SE_loc = trial.spikes_file.url
    VT_loc = trial.led_file.url
    print(SE_loc)
    print(VT_loc)
    return simplejson.dumps({'scatter_data': file_analysis.exportHistoExcel("test.xlsx") })
  return

这是我的python脚本(file_analysis.py):

from xlsxwriter.workbook import Workbook
def exportHistoExcel(SE_filelocation, VTfile_location, filename):

  print('anything?')

  data = getFiringRates(SE_filelocation, VTfile_location, generating_excel_file = True)
  print(data)

  print 'Writing to a new Excel file...'

  workbook = Workbook(filename)
  worksheet = workbook.add_worksheet()
  worksheet.write('A1', 'Bin (degrees)')
  worksheet.write('B1', '# of Spikes')
  worksheet.write('C1', '# of Samples')
  worksheet.write('D1', 'Time (sec)')
  worksheet.write('E1', 'Firing Rate')

  worksheet.write_column('A2', data[0])
  worksheet.write_column('B2', data[1])
  worksheet.write_column('C2', data[2])
  worksheet.write_column('D2', data[3])
  worksheet.write_column('E2', data[4])
  worksheet.write('A62', 360); worksheet.write('B62', '=$B$2')
  worksheet.write('C62', '=$C$2'); worksheet.write('D62', '=$D$2'); worksheet.write('E62', '=$E$2')


  histo = workbook.add_chart({'type': 'line'})
  histo.set_title({'name': 'Firing Rates'})
  histo.set_x_axis({'name': 'Bin (degrees)'})
  histo.set_y_axis({'name': 'Firing rate (sec^-1)'})
  histo.add_series({'values': '=Sheet1!$E$2:$E$61',
                  'line': {'color': 'black'},
                 'categories': '=Sheet1!$A$2:$A$61'})
  histo.set_legend({'delete_series': [0]})
  worksheet.insert_chart('F2', histo)

  print 'Excel file written'


  workbook.close()

  print 'workbook closed'

所有的print语句都有效,但是当我检查目录以查看test.xls是否已写入时,没有任何内容。

0 个答案:

没有答案