如何以相同的顺序重新排序项目并将其写入csv文件?

时间:2019-03-21 10:50:44

标签: jquery python-2.7 csv

我试图使应用程序允许读/写文件,然后重新排序项目。保存表单后,我将保存的数据写入csv文件。

但是,文件的输出项目内容与保存表单之前的顺序不同,甚至认为我添加了新项目或对现有项目重新排序。

模板: admin.html

$(document).ready(function() {
  var ul = `
					<ul class="list-inline in-item" style="padding: 10px;">
					  <li><a href="#"><i class="fa fa-plus-circle icon-add"></i></a></li>
					  <li><a href="#"><i class="fa fa-pencil-square-o icon-edit"></i></a></li>
					  <li><a href="#"><i class="fa fa-trash-o icon-remove"></i></a></li>
					  <li><a href="#"><i class="fa fa-arrows-v icon-move"></i></a></li>
					</ul>
				`;

  var sibling = ''

  /**
   * Show Action Icons on Mouse over and hide it
   * on Mouse out
   */
  $('body').on({
    mouseenter: function() {
      //stuff to do on mouse enter
      $(ul).insertBefore($(this).find('.item-head'));
    },
    mouseleave: function() {
      //stuff to do on mouse leave
      $(this).find('ul.list-inline').remove();
    }
  }, ".item");

  /**
   * Make Sortable
   */
  $('.item-container').on('mousedown', function() {

    $(".item-container").sortable({
      cursor: 'move'
    });
  })
  $('h3,p').on('click', function() {
    $(".item-container").sortable("destroy");
  });

  $('body').on('click', '.icon-add', function() {
    // Add Item
    items = `
				<div class="item">
				  <h3 class="item-head" contenteditable>[Type Item Here] [label]</h3>
				  <p contenteditable>[Type what it does]</p>
				</div>
			`;
    // $('body').append(item);
    $('.item-container').append(items);
    return false;
  });

  $('body').on('click', '.icon-edit', function() {
    // Edit on Item
  });

  $('body').on('click', '.icon-remove', function() {
    // Remove Item and its definition

  });

  $('body').on('click', '.icon-move', function() {
    // Move item to up or down
    // Remove Item and its definition
    sibling = $(this).parentsUntil(".item-container")[3];
    $(sibling).remove();
    return false;
  });

  /**
   * 
   * Saving the file
   */
  var val = '';
  var name = [];
  var nameVal = ''
  var definition = [];
  var definitionVal = [];
  var form = '';
  var Obj = {};

  $('#Save').on('click', function() {
    form = 'Customer'; // get from ID Form
    Obj.form = 'Customer';

    $('.item-container h3').each(function() {

      nameVal = $(this).text();
      definitionVal = $(this).next().text();
      Obj[nameVal] = definitionVal;

    });

    console.log(Obj);

    $.ajax({
      url: "/BuiltInHelp/Save",
      dataType: 'json',
      contentType: 'application/json',
      method: "POST",
      data: JSON.stringify(Obj),
      success: function(data) {
        console.log(data);
        location.reload(true);
      }
    });

  });

})
.item-head {
  color: #365efe;
}

.action-icon {
  float: left;
  margin-top: 25px;
  margin-left: -40px;
}

.icon-add {
  color: #4caf50;
}

.icon-edit {
  color: #00bcd4;
}

.icon-remove {
  color: #f44336;
}

.icon-move {
  color: #9e9e9e;
}

.in-item {
  display: block;
}

.out-item {
  display: none;
}

.list-inline>li:last-child {
  padding-right: 25px;
}

.list-inline {
  float: left;
  background: trasparent;
  position: absolute;
  left: -110px;
  top: 12px;
  height: 40px;
}

div.item {
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="col-sm-12">
  <div class="message"></div>
  <h3>Preview</h3>
  <button class="btn btn-primary" id="Save">Save</button>
  <div class="container" style="border: 1px solid #ccc;width: 70%;">
    <div class="row">
      <div class="col-xs-12 item-container sortable">
        <div class="item">
          <h3 class="item-head" style="float: left;">Customer [form]</h3>
          <p style="clear: both;">Customer is module for recording information related to customer such as Name, Address, Date of Birth, Place of Birth, ID Number, etc.</p>
        </div>
        <div class="item">
          <h3 class="item-head">First Name English [label]</h3>
          <p class="definition">The name that was given to you when you were born and that comes before your family name. This field accept only English Character.</p>
        </div>
        <div class="item">
          <h3 class="item-head">Salutation [label]</h3>
          <p>A greeting in words or actions, or the words used at the beginning of a letter or speech. This field has values such as Mr, Ms, Miss.</p>
        </div>
      </div>
    </div>
  </div>
  </form>
</div>

因此,从Form获取数据之后,我将使用Python脚本从后端写入文件。

views.py

import json
import os
import csv

@app.route('/BuiltInHelp/Save',methods=['GET','POST'])
def writeCSVs():

    if request.method=='POST':

        Columns = ['Form','Name','Type','Definition']
        string  = ''

        items = {key:value  for key,value in request.json.iteritems() if key != 'form'} 
        form = request.json.get('form')

        filename = form+'Ex.csv'

        # print "underneath this line is check if it is a file, \nfile exist or not "
        if os.path.isfile(filename):
            os.remove(filename)

        with open("%sEx.csv"%form,"w+") as f:
            # writeHeader(f)
            for col_header in Columns:
                string = string + "," + col_header
            f.write(string[1:]+'\n')
            # for item in branchObj:
            string = ''
            for key,value in items.iteritems():
                string += form + "," + key + "," + " " + ","+value.replace(',','') + '\n'

            f.write(string+'\n')

        return ''
    return ''

无需在上面的代码段中进行进一步的重新排序或添加更多项,最终的csv文件的输出将与提交表单之前进行不同的重新排序,或者在后续的Save中对该项进行了随机重新排序。

Output of the file

如上所述,如何保存表单中保存的数据项与提交之前相同的顺序?谢谢

0 个答案:

没有答案