Autore Topic: Esportare una tabella del database in csv  (Letto 434 volte)

Offline zak84

  • Utente normale
  • ***
  • Post: 165
  • Respect: +2
    • Mostra profilo
Esportare una tabella del database in csv
« il: 09 Luglio 2013, 17:18:56 CEST »
0
Ciao ragazzi, ho un problema nell'esportazione in csv di una tabella del db.
Ho trovato poche guide online e quasi tutte legate a questo opencsv (lo conoscete?).
Ho implementato ma non funziona perché non trova la classe del jar che ho scaricato e incluso nel java buold path come jar esterno.

Codice: [Seleziona]
                if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
                    Toast.makeText(this,getResources().getString(R.string.errore_scheda), Toast.LENGTH_LONG).show();
                    findViewById(R.id.save).setVisibility(4);
                    return false;
                }
                File root = android.os.Environment.getExternalStorageDirectory();
                File exportDir=new File(root.getAbsolutePath()+"/mio_csv");       
        if(!exportDir.exists()){
            exportDir.mkdirs();
        }
        SimpleDateFormat dateFormat=new SimpleDateFormat("dd-MM-yyyy",Locale.ITALY);
        Date date = new Date();
        String data=dateFormat.format(date);
        File file=new File(exportDir,data+"_"+quanto+".csv");
        try{
            file.createNewFile();
            CSVWriter csvWrite=new CSVWriter(new FileWriter(file));
            db.open();
            Cursor curCSV=db.prendi_preventivi();
            csvWrite.writeNext(curCSV.getColumnNames());
            while(curCSV.moveToNext()){
                String arrStr[]={curCSV.getString(1),curCSV.getString(2),curCSV.getString(3),curCSV.getString(4),curCSV.getString(5),curCSV.getString(6),curCSV.getString(7),curCSV.getString(8),curCSV.getString(9)};
                csvWrite.writeNext(arrStr);
            }
            db.close();
            csvWrite.close();
            Toast.makeText(this,getResources().getString(R.string.file_creato)+file.toString(), Toast.LENGTH_LONG).show();
            findViewById(R.id.save).setVisibility(4);
            return true;
        }catch(Exception sqlEx){
            Log.e("MainActivity",sqlEx.getMessage(),sqlEx);
            Toast.makeText(this,getResources().getString(R.string.errore_scheda), Toast.LENGTH_LONG).show();
            findViewById(R.id.save).setVisibility(4);
            return true;
        }

mi potete aiutare? magari importo io male.
l'errore è:
Could not find class 'au.com.bytecode.opencsv.CSVWriter', referenced from method it.miaapp.Lista_preventivi.esporta_csv


avete altre idee su come fare questa cosa?

Grazie.

Offline bradipao

  • Moderatore globale
  • Utente storico
  • *****
  • Post: 4043
  • keep it simple
  • Respect: +567
    • Github
    • Google+
    • bradipao
    • Mostra profilo
  • Dispositivo Android:
    Nexus 5
  • Play Store ID:
    Bradipao
  • Sistema operativo:
    W7
Re:Esportare una tabella del database in csv
« Risposta #1 il: 09 Luglio 2013, 18:44:38 CEST »
0
Prova ad usare direttamente il CSVWriter.java nel progetto:

Codice (Java): [Seleziona]
package scrivi.qua.il.package.che.vuoi;

/**
Copyright 2005 Bytecode Pty Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/


/*
* The code copied from [url=http://opencsv.sourceforge.net/]opencsv - Frequently Asked Questions[/url]
*
* While incorporating into secrets, the following changes were made:
*
* - removed the following methods to keep the bytecode smaller:
*   writeAll(), all methods related to sql
*/


import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

/**
* A very simple CSV writer released under a commercial-friendly license.
*
* @author Glen Smith
*
*/

public class CSVWriter {

   private PrintWriter pw;

   private char separator;

   private char quotechar;

   private char escapechar;

   private String lineEnd;

   /** The character used for escaping quotes. */
   public static final char DEFAULT_ESCAPE_CHARACTER = '"';

   /** The default separator to use if none is supplied to the constructor. */
   public static final char DEFAULT_SEPARATOR = ',';

   /**
    * The default quote character to use if none is supplied to the
    * constructor.
    */

   public static final char DEFAULT_QUOTE_CHARACTER = '"';

   /** The quote constant to use when you wish to suppress all quoting. */
   public static final char NO_QUOTE_CHARACTER = '\u0000';

   /** The escape constant to use when you wish to suppress all escaping. */
   public static final char NO_ESCAPE_CHARACTER = '\u0000';

   /** Default line terminator uses platform encoding. */
   public static final String DEFAULT_LINE_END = "\n";

   /**
    * Constructs CSVWriter using a comma for the separator.
    *
    * @param writer
    *            the writer to an underlying CSV source.
    */

   public CSVWriter(Writer writer) {
       this(writer, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER,
           DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END);
   }

   /**
    * Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
    *
    * @param writer
    *            the writer to an underlying CSV source.
    * @param separator
    *            the delimiter to use for separating entries
    * @param quotechar
    *            the character to use for quoted elements
    * @param escapechar
    *            the character to use for escaping quotechars or escapechars
    * @param lineEnd
    *           the line feed terminator to use
    */

   public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
       this.pw = new PrintWriter(writer);
       this.separator = separator;
       this.quotechar = quotechar;
       this.escapechar = escapechar;
       this.lineEnd = lineEnd;
   }

   /**
    * Writes the next line to the file.
    *
    * @param nextLine
    *            a string array with each comma-separated element as a separate
    *            entry.
    */

   public void writeNext(String[] nextLine) {

     if (nextLine == null)
        return;

       StringBuffer sb = new StringBuffer();
       for (int i = 0; i < nextLine.length; i++) {

           if (i != 0) {
               sb.append(separator);
           }

           String nextElement = nextLine[i];
           if (nextElement == null)
               continue;
           if (quotechar !=  NO_QUOTE_CHARACTER)
              sb.append(quotechar);
           for (int j = 0; j < nextElement.length(); j++) {
               char nextChar = nextElement.charAt(j);
               if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
                 sb.append(escapechar).append(nextChar);
               } else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) {
                 sb.append(escapechar).append(nextChar);
               } else {
                   sb.append(nextChar);
               }
           }
           if (quotechar != NO_QUOTE_CHARACTER)
              sb.append(quotechar);
       }

       sb.append(lineEnd);
       pw.write(sb.toString());

   }

   /**
    * Flush underlying stream to writer.
    *
    * @throws IOException if bad things happen
    */

   public void flush() throws IOException {

       pw.flush();

   }

   /**
    * Close the underlying stream writer flushing any buffered content.
    *
    * @throws IOException if bad things happen
    *
    */

   public void close() throws IOException {
       pw.flush();
       pw.close();
   }

}
NON rispondo a domande nei messaggi privati
Bradipao @ Play Store

Offline zak84

  • Utente normale
  • ***
  • Post: 165
  • Respect: +2
    • Mostra profilo
Re:Esportare una tabella del database in csv
« Risposta #2 il: 09 Luglio 2013, 19:15:06 CEST »
0
'inchia vero!
Funziona  :-*