Visualizzazione dei risultati da 1 a 9 su 9
  1. #1

    [Java] Leggere un file CSV creato con EXCEL

    Salve a tutti. Ho fatto un programma che mi legge il contenuto di un file .csv.
    Pensavo funzionasse sia per quelli prodotti con il programma microsoft excel, sia con quelli prodotti da Open Office. Invece hanno una struttura differente, infatti:

    OPEN OFFICE:
    "NOME ","COGNOME","DATA"

    EXCEL
    NOME; COGNOME; DATA

    il mio programma non riesce a distinguere le varie parole del file csv creato da excel.
    codice:
    /**
    	 * Take HEAD row of CSV file
    	 * 
    	 * @param reader
    	 *            to file
    	 * @param nRow
    	 *            of row to analyze
    	 * @return HeadRow 
    	 * if row = null -> the operation is failed
    	 */
    	private static ArrayList<String> getCsvHeadRow(File file, int nRow) {
    
    		// Take reader
    		CSVReader reader = getReader(file);
    		ArrayList<String> row = new ArrayList<String>();
    		try {
    			String[] nextLine = reader.readNext();
    
    			// Take an row
    			for (int j = 0; j < nextLine.length; j++) {
    				row.add(trimAndLowerCase(nextLine[j]));
    			}
    		}
    		catch (IOException e) {
    			e.printStackTrace();
    			row = null;
    		}
    		return row;
    	}// end of method
    Praticamente con un file csv prodotto da Open Office alla fine ottengo:
    row1 = nome
    row2 = cognome
    row3 = data
    come è giusto che sia

    Con il file csv prodotto da Excel ottengo
    row1= "nome; cognome; data".

    Qualcuno sa aiutarmi????

  2. #2
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    ovviamente: uno usa un separatore (la virgola), l'altro un separatore diverso (il punto e virgola). Suppongo che la libreria che stai utilizzando, da cui CVSReader è stata presa, consenta di specificare che separatore utilizzare... se non ritieni fattibile scansionare la prima riga del documento e determinare il possibile separatore, quindi utilizzare quello per il parsing, puoi sempre impostare Excel (in verità si deve impostare l'intero sistema) affinchè venga utilizzata la virgola come delimitatore (la modifica avviene nel pannello di controllo, nelle impostazioni di orario/regione/linguaggio)
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  3. #3
    Grazie mille, non lo sapevo

  4. #4
    Ho provato a fare come mi hai detto, solo che non funziona, è come se non avessi modificato nulla...



    Invece di prendermi solo una parola, come code, mi prende l'intera riga...
    Come posso fare????

  5. #5
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    prova un po' ad aprire il file con WordPad e vedi se effettivamente viene salvato con i delimitatori attesi... poi non riesco a capire l'utilità di 2 righe di codice: che senso hanno
    codice:
    CSVReader ExcelReader = new CSVReader(readerExcel, ';');
    ExcelReader = getReader(file);
    ?

    La prima definizione mi sta bene, se poi non vi fosse la ri-assegnazione una riga sotto. In pratica, getReader(file) è quella che se la comanda...
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  6. #6
    Allora aperto con wordPad viene esattamente questo:
    code;description;unit;price

    Cerco di spiegare perchè ho inserito quelle due righe.
    Allora con questo codice mi separa queste parole: "NOME ","COGNOME","DATA"

    codice:
    /**
    	 * Take HEAD row of CSV file
    	 * 
    	 * @param reader
    	 *            to file
    	 * @param nRow
    	 *            of row to analyze
    	 * @return HeadRow 
    	 * if row = null -> the operation is failed
    	 */
    	private static ArrayList<String> getCsvHeadRow(File file, int nRow) {
    
    		// Take reader
    		CSVReader reader = getReader(file);
    		ArrayList<String> row = new ArrayList<String>();
    		try {
    			String[] nextLine = reader.readNext();
    
    			// Take an row
    			for (int j = 0; j < nextLine.length; j++) {
    				row.add(trimAndLowerCase(nextLine[j]));
    			}
    		}
    		catch (IOException e) {
    			e.printStackTrace();
    			row = null;
    		}
    		return row;
    	}// end of method
    Poichè io devo separare delle parole scritte in questo modo: NOME; COGNOME; DATA
    Mi avevi detto di utilizzare il metodo con il quale settare il separatore, cioè questo
    codice:
    CSVReader ExcelReader = new CSVReader(readerExcel, ';');
    Quindi ho modificato il codice in questo modo:
    codice:
    	/**
    	 * Take HEAD row of CSV file
    	 * 
    	 * @param reader
    	 *            to file
    	 * @param nRow
    	 *            of row to analyze
    	 * @return HeadRow 
    	 * if row = null -> the operation is failed
    	 */
    	private static ArrayList<String> getCsvHeadRow(File file, int nRow) {
    
    		// Take reader
    		Reader readerExcel = new Reader() {
    			
    			@Override
    			public int read(char[] buf, int offset, int count) throws IOException {
    				// TODO Auto-generated method stub
    				return 0;
    			}
    			
    			@Override
    			public void close() throws IOException {
    				// TODO Auto-generated method stub
    				
    			}
    		};
    		
    		CSVReader ExcelReader  = new CSVReader(readerExcel, ';');
    		ExcelReader = getReader(file);
    		ArrayList<String> row = new ArrayList<String>();
    		try {
    			String[] nextLine = ExcelReader.readNext();
    
    			// Take an row
    			for (int j = 0; j < nextLine.length; j++) {
    				row.add(trimAndLowerCase(nextLine[j]));
    			}
    		}
    		catch (IOException e) {
    			e.printStackTrace();
    			row = null;
    		}
    		return row;
    	}// end of method
    
    /**
    	 * Take reader to file
    	 * 
    	 * @param file
    	 *            from with to take reader
    	 * 
    	 * @return reader of file
    	 */
    	private static CSVReader getReader(File file) {
    		CSVReader reader = null;
    		try {
    			reader = new CSVReader(new FileReader(file));
    			return reader;
    		}
    		catch (FileNotFoundException e) {
    			e.printStackTrace();
    			return null;
    		}
    	}// end of method
    Ho copiato tutto il codice per rendere più leggibile il programma.
    Hai capito un po' meglio il mio metodo?
    Solo che è come se non avessi cambiato nulla

  7. #7
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    per forza: la seconda riga delle due che ti ho segnalato vanifica la prima, o meglio, devi vedere che fa esattamente il metodo che chiami nella seconda riga.

    EDITO:
    codice:
    private static CSVReader getReader(File file) {
    		CSVReader reader = null;
    		try {
    			reader = new CSVReader(new FileReader(file));
    			return reader;
    		}
    		catch (FileNotFoundException e) {
    			e.printStackTrace();
    			return null;
    		}
    	}
    ecco, qui ritorni un nuovo CSVReader, ma creato senza parametri... per cui magari lo ricrea con il default diverso da quello che ti aspetteresti.
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  8. #8
    Ti Ringrazio infinitamente!!!!!!!!!!!!!!

    Ho risolto in questo modo

    codice:
    private static ArrayList<String> getCsvHeadRowExcel (File file, int nRow){
    		
    		//take reader
    		Reader readerExcel = new Reader() {
    			
    			@Override
    			public int read(char[] buf, int offset, int count) throws IOException {
    				// TODO Auto-generated method stub
    				return 0;
    			}
    			
    			@Override
    			public void close() throws IOException {
    				// TODO Auto-generated method stub
    				
    			}
    		};
    		
    		CSVReader excelReader = new CSVReader(readerExcel, ';');
    		excelReader  = getReaderExcel(file);
    		ArrayList<String> row = new ArrayList<String>();
    		try {
    			String[] nextLine = excelReader.readNext();
    
    			// Take an row
    			for (int j = 0; j < nextLine.length; j++) {
    				row.add(trimAndLowerCase(nextLine[j]));
    			}
    		}
    		catch (IOException e) {
    			e.printStackTrace();
    			row = null;
    		}
    		return row;
    	}
    /**
    	 * Take reader to file
    	 * 
    	 * @param file
    	 *            from with to take reader
    	 * 
    	 * @return reader of file
    	 */
    	private static CSVReader getReaderExcel(File file) {
    		CSVReader reader = null;
    		try {
    			reader = new CSVReader(new FileReader(file), ';');
    			return reader;
    		}
    		catch (FileNotFoundException e) {
    			e.printStackTrace();
    			return null;
    		}
    	}// end of method
    Grazie ancora per l'aiuto, non sai da quanto tempo ci stavo dietro...
    Alla prossima

  9. #9
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    sì, resta comunque una doppia riga in cui avviene esattamente la stessa cosa: per come è strutturato adesso, questo:
    codice:
    CSVReader excelReader = new CSVReader(readerExcel, ';');
    excelReader  = getReaderExcel(file);
    potresti comprimerlo in questo:
    codice:
    CSVReader excelReader = getReaderExcel(file);
    oppure riscrivere il metodo getReaderExcel così:
    codice:
    private static CSVReader getReaderExcel(File file, char sep) {
    		CSVReader reader = null;
    		try {
    			reader = new CSVReader(new FileReader(file), sep);
    			return reader;
    		}
    		catch (FileNotFoundException e) {
    			e.printStackTrace();
    			return null;
    		}
    	}// end of method
    e richiamarlo così:

    codice:
    CSVReader excelReader = getReaderExcel(file, ';');
    non sia mai che un domani ti cambino il carattere separatore: in questo modo ti basta andare a modificare l'invocazione e non un qualche metodo...
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.