Friday, July 19, 2013

Re: export .csv file from database

Two things: 
First, Ms Excel sucks. From that attached screenshot it's obvious that it thought it was a space separated file. When actually using MS Office, I recommend that you add `quoting=csv.QUOTE_ALL` to all csv writers. 

Second, the HttpResponse object is file-like. You don't need to jump through all the hoops. And MS Office is going to ignore your encoding anyway, so there's no point in trying to fix it.

On Jun 17, 2013, at 9:44 AM, roopasingh250@gmail.com wrote:

views.py

@login_required  def export_csv(request):      user = request.user      # heading columns      headerrow = ['Filename', 'Description','Notes other','Reporter Name']      allrows = []      today = datetime.datetime.today() # default to show today      reports = Report.objects.filter(user=user)      reports = reports.filter(created_date_time__year=today.year)      for report in reports:          row = []          row.append(report.report_number);          row.append(report.report_description);          row.append(report.notes_other);          row.append(report.reporter_name);          allrows.append(row)      # setup CSV export      response = HttpResponse(mimetype='text/csv')      filename = "%s-%s.csv" % ('Daily-reports', datetime.datetime.now().strftime('%Y-%m-%d'))      response['Content-Disposition'] = 'attachment; filename=%s' % filename      writer = UnicodeWriter(response, encoding='utf-8')      writer.writerow(headerrow)      for writerow in allrows:          writer.writerow(writerow)      return response

csv_unicode.py

import csv, codecs, cStringIO class UnicodeWriter: def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([unicode(s).encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row)

The above code is exporting the database data into .csv file.

Problem i am facing is,the exported data like Filename,Description,Notes Others,Reporter Name are exported in separate cell.Will show the output i am getting and required output.

You can see my existing and required format.

I had attached two format,file name existing_csv is the output file i ma getting,required_csv is the .csv file i am expecting.

Need some ones help.

Peter of the Norse



No comments:

Post a Comment