Hi Stifan.
I do it like that, for example for a table called cm1:
import os
from cStringIO import StringIO
#Original table
db.define_table('cm1',
Field('code', type='integer'),
Field('title_en', type='string'),
Field('title_it', type='string'))
#Table for update - Useful for not changing id's, and also if in your table
you've some referenced fields.
db.define_table('cm1_for_update',
Field('code', type='integer'),
Field('title_en', type='string'),
Field('title_it', type='string')).
def update_cm1():
form = SQLFORM.factory(Field('csvfile','upload',uploadfield=False))
form.process()
if form.accepted:
csvtxt = request.vars.csvfile.file.read()
#SET FILE FOR IMPORT - It's possible that you've to change some
data in your csv file before import
#Replacing decimal separator ',' by '.'
csvtxt = csvtxt.replace(',', '.')
#Replacing field separator ';' by ','
csvtxt = csvtxt.replace(';', ',')
#Replacing field names
csvtxt = csvtxt.replace('Codice_N,Descrizione_Breve,Descr_Inglese',
'cm1.code,cm1.title_it,cm1.title_en')
db(db.cm1_for_update.id > 0).delete() #Cancel all records of
cm1_for_update table
db.cm1_for_update.import_from_csv_file(StringIO(csvtxt)) #Import
CSV file in cm1_for_update table
cm1s_for_update = db().select(db.cm1_for_update.ALL)
for cm1_for_update in cm1s_for_update:
n_rows = db(db.cm1.code == cm1_for_update.code).count() #Verify
how many records are already in the cm1 table
if n_rows == 1: #Update
db(db.cm1.code == cm1_for_update.code).update(
title_en = cm1_for_update.title_en,
title_it = cm1_for_update.title_it)
elif n_rows == 0: #Insert
db.cm1.insert(
code=cm1_for_update.code,
title_en = cm1_for_update.title_en,
title_it = cm1_for_update.title_it)
elif n_rows > 1:
message=('Error, there are duplicated rows.')
break
Il giorno giovedì 12 gennaio 2017 16:46:35 UTC+1, 黄祥 ha scritto:
>
> imagine table with thousands data
> e.g.
> name quantity price
> product a 10 10000
> product b 15 11000
>
> and every several months (5 or 6 months) the supplier send the update of
> the product price
> is it possible to import csv that can update some existing data (*not
> insert new data*) in existing table?
> e.g.
> TABLE product
> name,price
> product a,11000
> product b,12000
>
> END
>
> thanks and best regards,
> stifan
>
--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to the Google Groups
"web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.