Cvt_xls // permet de convertir un fichier csv en fichier excel

Description

Ce petit programme permet de convertir des fichiers à plats, type CSV, en belle feuilles Excel. Les données issues de base de données, sont recopiés par valeur dans un fichier Excel, qui peut être préformaté... . Un format par défaut est proposé: Entête blanc sur noir et ligne de données pair : blanc impai gris.

//============================== Objet ==================================
// Permet de convertir un fichier CSV en fichier EXCEL
//============================== Parametres =============================
// . 1 . le fichier CSV à convertir CSV= obligatoire
// . 3 . le charactère de séparation SEP= default ;
// . 4 . le formatage de la première ligne (titre ) TIT= default O
// . 5 . le nom de la feuille de calcul SHT= default nom CSV
// . 6 . le fichier XLS de sortie (non obligatoire) XLS= default nom CSV
// . 7 . le fichier modèle (données copiées uniq.) MDL= option
// . 8 . Mise en forme (1 ligne sur 2 grisée) MEF= option
//=======================================================================

Exemple d'utilisation en ligne:
cvt_xls CSV=<fichier.csv> SEP=; TIT=O SHT=<nom feuilleCalcul> XLS=<fichier.xls>

Source / Exemple :


//=======================================================================
// cvt_xls.java 
//============================== Objet ==================================
// Permet de convertir un fichier CSV en fichier EXCEL
//============================== Parametres =============================
// . 1 . le fichier CSV à convertir                 CSV=  obligatoire
// . 3 . le charactère de séparation                SEP=  default ;
// . 4 . le formatage de la première ligne (titre ) TIT=  default O
// . 5 . le nom de la feuille de calcul             SHT=  default nom CSV
// . 6 . le fichier XLS de sortie (non obligatoire) XLS=  default nom CSV
// . 7 . le fichier modèle (données copiées uniq.)  MDL=  option
// . 8 . Mise en forme (1 ligne sur 2 grisée)       MEF=  option   
//=======================================================================
//  17/10/2007 -- strs -- creation    
//  06/03/2008 -- strs -- ajout de l'option d'utiliser un modèle 
//  26/05/2008 -- strs -- si la valeur commence par = c'est un nombre
//=======================================================================

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

import jxl.CellType;
import jxl.CellView;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.CellFormat;
import jxl.format.Colour;
import jxl.format.ScriptStyle;
import jxl.format.UnderlineStyle;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.NumberCell;

public class cvt_xls {

  public static void main(String[] args) {

    String nom_fic_csv="";
    String separateur=";";
    String titre="O";
    String nom_fic_xls="";
    String nom_feuil="";
    boolean ExistSheet=false;
    String debug="N";
    String mise_en_forme="O";
    String fic_xls_modele="";

    String fic_csv="";     //le nom du fichier CSV sans le chemin
    String typ_fic_csv=""; //le suffixe du fichier CSV
    String rep_fic="";     //le répertoire de travail
    
    
///////////////////////////////////////////////////////////
//     Lecture et contrôle des paramètres
///////////////////////////////////////////////////////////
    //System.out.println("AGUMENTS ::: " + args.length);
    for (int i=0; i<args.length; i++) 
    {
      //System.out.println(args[i]);
       
      if ( args[i].substring(0,4).equals("CSV=") )
      {
        nom_fic_csv= args[i].substring(4);
      }
      if ( args[i].substring(0,4).equals("SEP=") )
      {
        separateur= args[i].substring(4);
      }
      if ( args[i].substring(0,4).equals("TIT=") )
      {
         titre= args[i].substring(4);
      }
      if ( args[i].substring(0,4).equals("XLS=") )
      {
        nom_fic_xls= args[i].substring(4);
      }
      if ( args[i].substring(0,4).equals("SHT=") )
      {
        nom_feuil= args[i].substring(4);
      }
      if ( args[i].substring(0,4).equals("MEF=") )
      {
        mise_en_forme= args[i].substring(4);
      }
      if ( args[i].substring(0,4).equals("MDL=") )
      {
        fic_xls_modele= args[i].substring(4);
      }
      if ( args[i].substring(0,4).equals("DBG=") )
      {
        debug= args[i].substring(4);
      }
    }
    //Le fichier CSV est obligatoire
    if ((nom_fic_csv.equals("")) && (nom_fic_csv==null)) {
      System.out.println("cvt_xls  CSV=<fichier.csv> SEP=; TIT=O  SHT=<nom feuilleCalcul> XLS=<fichier.xls>");
      System.out.println("le parametre CSV=<fichier.csv> est obligatoire");
      System.exit(1);
    }
          		

    //Test de l'ouverture du fichier CSV
    Fichier fichier_csv= new Fichier(nom_fic_csv);
    if (!fichier_csv.lirePossible()) {
      System.out.println(nom_fic_csv+" "+fichier_csv.proprietes());
      System.exit(0);
    }
    else
    {
      // TEST OK On récupère le nom de fichier, le type et le chemin 
      fic_csv = fichier_csv.getName();  
      typ_fic_csv = fic_csv.substring(fic_csv.lastIndexOf('.')+1);
      rep_fic     = fichier_csv.parent();
    }

    //Si un modele doit être utilise on test la présence du fichier modele
    if (!fic_xls_modele.equals("")) {
    	Fichier fichier_mod= new Fichier(fic_xls_modele);
        if (!fichier_mod.lirePossible()) {
            System.out.println(fic_xls_modele+" "+fichier_mod.proprietes());
            System.out.println("Lecture du fichier modèle impossible :: conversation normale");
            fic_xls_modele="";
        } else { mise_en_forme="N";	titre="N"; }
    }
    

    
    // Le nom du fichier XLS de sortie s'il existe
    if ((nom_fic_xls.equals("")) || (nom_fic_xls==null)) {
      nom_fic_xls=nom_fic_csv;
      if ( typ_fic_csv.toUpperCase().equals("CSV") ) 
      {
        nom_fic_xls= nom_fic_xls.substring(0,nom_fic_xls.lastIndexOf('.')+1)+"xls";
      }
      else
      {
        nom_fic_xls=nom_fic_xls+".xls";
      }
    };

    // Le nom de la feuille de calcul qui sera ajoutée
    if ((nom_feuil.equals("")) || (nom_feuil==null)) {
      //on prend le nom du fichier CSV si le parametre est nul
      nom_feuil=fic_csv.substring(0,fic_csv.lastIndexOf('.'));
    };
      
    if (debug.equals("O"))
    {
      System.out.println("FICHIER D'ENTREE         =  " + nom_fic_csv );
      System.out.println("FICHIER DE SORTIE EXCEL  =  " + nom_fic_xls );
      System.out.println("SEPARATEUR               =  " + separateur );
      System.out.println("FORMATAGE TITRE          =  " + titre );
      System.out.println("MISE EN FORME DES CELL   =  " + mise_en_forme );
      System.out.println("NOM DE LA FEUILLE        =  " + nom_feuil );
      System.out.println("NOM DU FICHIER MODELE    =  " + fic_xls_modele );
    }
    
///////////////////////////////////////////////////////////
//     Initialisation du Workbook
///////////////////////////////////////////////////////////
    try {
      WritableWorkbook fichier_obj_xls;
      //Est ce que le fichier XLS existe ?
      Fichier fichier_xls= new Fichier(nom_fic_xls);
      int NewSheet = 0;
      if (fichier_xls.lirePossible()) 
      {   
         //s'il existe on en le "créé" en le prenant en copie
         Workbook workbook = Workbook.getWorkbook(new File(nom_fic_xls));
         String[] sheetList;
         String sheetName;
         sheetList=workbook.getSheetNames();
         for(int i=0;i<sheetList.length;i++){
             sheetName=sheetList[i];
             if (debug.equals("O")) System.out.println(i + " FEUILLE XLS EXISTANT =  " + sheetName );
             if (sheetName.equals(nom_feuil)) {ExistSheet=true; break;}
             NewSheet=i+1;
         }
         fichier_obj_xls = Workbook.createWorkbook(new File(nom_fic_xls), workbook);
      }
      else
      {
    	 //Le fichier excel n'existe pas :: on applique le modèle s'il est renseigné 
    	  if (!(fic_xls_modele.equals("")) ) {
    		  Fichier fichier_mdl= new Fichier(fic_xls_modele);
    	      if (fichier_mdl.lirePossible()) 
    	      {   
    	         //s'il existe on en le "créé" en le prenant en copie
    	         Workbook workbook_mdl = Workbook.getWorkbook(new File(fic_xls_modele));
    	         String[] sheetList_mdl;
    	         String sheetName_mdl;
    	         sheetList_mdl=workbook_mdl.getSheetNames();
    	         for(int i=0;i<sheetList_mdl.length;i++){
    	             sheetName_mdl=sheetList_mdl[i];
    	             if (debug.equals("O")) System.out.println(i + " FEUILLE DU MODELE EXISTANT =  " + sheetName_mdl );
    	             if (sheetName_mdl.equals(nom_feuil)) {ExistSheet=true; break;}
    	             NewSheet=i+1;
    	         }
    	         fichier_obj_xls = Workbook.createWorkbook(new File(nom_fic_xls), workbook_mdl);
    	      }
    	      else fichier_obj_xls = Workbook.createWorkbook(new File(nom_fic_xls)); // le fichier modèle n'est pas lisible
    	  } else fichier_obj_xls = Workbook.createWorkbook(new File(nom_fic_xls)); // le fichier modèle n'est pas renseigné
      }
      
      //On initialise une feuille de Calcul
      WritableSheet sheet;
      
      if (ExistSheet)
      {
    	 //La feuille existe :: on écrit par dessus
    	 sheet = fichier_obj_xls.getSheet(NewSheet);  
    	 if (debug.equals("O")) System.out.println("PRISE EN COMPTE DE LA FEUILLE EXISTANTE (" + NewSheet + ") "  + nom_feuil );
      }
      else
      {    	  
    	  sheet = fichier_obj_xls.createSheet(nom_feuil, NewSheet);
    	  if (debug.equals("O")) System.out.println("CREATION LA FEUILLE (" + NewSheet + ") "  + nom_feuil );
      }
  
      //Crée le format d&#8217;une cellule TITRE ::    format_titre
      WritableFont courier10_titre    = new WritableFont(WritableFont.COURIER, 
                                                         10,
                                                         WritableFont.BOLD, 
                                                         false, 
                                                         UnderlineStyle.NO_UNDERLINE,
                                                         Colour.WHITE, 
                                                         ScriptStyle.NORMAL_SCRIPT);
                                                    
      WritableCellFormat format_titre = new WritableCellFormat(courier10_titre);
      format_titre.setBackground(Colour.GRAY_80 );
      format_titre.setBorder(Border.ALL, BorderLineStyle.THIN);
      
      
      //Crée le format d&#8217;une cellule NORMAL format_normal ligne paire et impaire
      WritableFont courier10 = new WritableFont(WritableFont.COURIER, 
                                                10,
                                                WritableFont.NO_BOLD,
                                                false, 
                                                UnderlineStyle.NO_UNDERLINE,
                                                Colour.BLACK, 
                                                ScriptStyle.NORMAL_SCRIPT);
      // format_normal ligne blanche paire 
      WritableCellFormat format_normal_blanc = new WritableCellFormat(courier10);
      format_normal_blanc.setBorder(Border.ALL, BorderLineStyle.THIN);
      // format_normal ligne grisée impaire 
      WritableCellFormat format_normal_gris = new WritableCellFormat(courier10);
      format_normal_gris.setBackground(Colour.GRAY_25 );
      format_normal_gris.setBorder(Border.ALL, BorderLineStyle.THIN);
      
///////////////////////////////////////////////////////////
//     Lecture du fichier CSV et écriture dans Excel
///////////////////////////////////////////////////////////
      BufferedReader lecteurAvecBuffer = null;
      String ligne;
      int num_lig =0;
      int num_col =0;
      int max_col =0;
      String  value_cell="";
      String  mem_value_cell="";
      int largeur_col[];
      largeur_col = new int[255];
      lecteurAvecBuffer = new BufferedReader (new FileReader(nom_fic_csv));
      while ((ligne = lecteurAvecBuffer.readLine()) != null ) {
        StringTokenizer st = new StringTokenizer(ligne, separateur,true);
        int imax=(st.countTokens()-1)/2; //car st.countTokens() est reclaculé à chaque itération...
        if (debug.equals("O"))  System.out.println("LIGNE : " + ligne + " Nb elements: " + st.countTokens());

        while ( st.countTokens()>0 )
        {
          WritableCell cell = null;
          
          value_cell=st.nextToken();
          if ((debug.equals("O")) && (num_lig<=5) ) System.out.println("CELLULE : " + num_col + "," + num_lig + " = " + value_cell);
          if ((debug.equals("O"))) System.out.println(value_cell.substring(1,value_cell.length()));
          if ( (value_cell.equals(separateur)) && (mem_value_cell.equals(separateur)) ) {
	          value_cell=" ";
          }
          else {
	          mem_value_cell=value_cell;
          }
          if (!value_cell.equals(separateur))
          {
            if (largeur_col[num_col]<=value_cell.length()) 
            {
              largeur_col[num_col]=value_cell.length();
            }
            if ((debug.equals("O"))) System.out.println("TYPE DE LA CELLULE : " + num_col + "," + num_lig + " = " + sheet.getWritableCell(num_col, num_lig).getType().toString());
            
            // La feuille existe :: on recopie uniquement la valeur dans la cellule
            if (ExistSheet) {
              cell = sheet.getWritableCell(num_col,num_lig);
              // on  mémorise le format de la cellule pour les réappliquer ensuite
              CellFormat mem_cell_format = cell.getCellFormat();
              if ((debug.equals("O"))) System.out.println( "BackgroundColour = " + mem_cell_format.getBackgroundColour().toString() );
              // on remplace le nombre
              if (cell.getType() == CellType.NUMBER )
              {
            	jxl.write.Number n = (jxl.write.Number) cell;
            	double aDouble = Double.parseDouble(value_cell);
                n.setValue( aDouble );
                
              }

              // on remplace le label
              if (cell.getType() == CellType.LABEL) 
              {
                Label lc = (Label) cell;
                lc.setString(value_cell);
              }
              cell.setCellFormat(mem_cell_format);
              //on créé la cellule si elle est vide 
              if (cell.getType() == CellType.EMPTY)
              {
            	 sheet.addCell(new Label(num_col, num_lig,value_cell));            	 
            	 if (!mem_cell_format.equals(null)) sheet.getWritableCell(num_col,num_lig).setCellFormat(mem_cell_format);
              }
              if (value_cell.substring(0,1).equals("=") )
              {
            	double aDouble = Double.parseDouble(value_cell.substring(1,value_cell.length()));
            	sheet.addCell(new Number(num_col,num_lig,aDouble));
                sheet.getWritableCell(num_col,num_lig).setCellFormat(mem_cell_format);
              }

              num_col++;
            }
            // La feuille n'existe pas :: on créé la cellule
            else {
            	sheet.addCell(new Label(num_col, num_lig,value_cell));
            	num_col++;
            }
          }  	
          
        }
        num_lig++;
        if (num_col > max_col) max_col=num_col;
        num_col=0;
      }
      lecteurAvecBuffer.close();

///////////////////////////////////////////////////////////
//     Mise en forme du fichier Excel
///////////////////////////////////////////////////////////
      if (mise_en_forme.equals("O"))
      {
        // Mise en forme des cellule
        for ( int i= 0; i<=max_col; i++)
        {
          for ( int j= 0; j<num_lig; j++)
          {
	        if (titre.equals("O"))
	        {
		         if (j==0) {sheet.getWritableCell(i,j).setCellFormat(format_titre);}
		         else { if (j%2==1) {sheet.getWritableCell(i,j).setCellFormat(format_normal_blanc);}
		                else {sheet.getWritableCell(i,j).setCellFormat(format_normal_gris);}
	                }
	        }
	        else
	        {
		         if (j%2==0) {sheet.getWritableCell(i,j).setCellFormat(format_normal_blanc);}
		         else {sheet.getWritableCell(i,j).setCellFormat(format_normal_gris);}
	        }
	      }
        }
        // Ajustement de la largeur des colonnes
        CellView cv = new CellView();
        for ( int i= 0; i<=max_col; i++)  
        {
          if (debug.equals("O")) System.out.println("Longueur max colone " + i + " : " + largeur_col[i] );
          if (largeur_col[i] ==0)
          { 
            sheet.removeColumn(i);
          }
          else
          {
            cv.setSize(largeur_col[i] * 340);
            sheet.setColumnView(i, cv);
          }
        }
      }
      fichier_obj_xls.write(); 
      fichier_obj_xls.close(); 
    }
    catch(IOException e) {
      System.out.println("Erreur I/O: "+e); }
    catch(WriteException e) {
      System.out.println("Erreur d'écriture: "+e); }
    catch(BiffException e) {
      System.out.println("Erreur Excel: "+ e); }

  } //Fin du Main

} //Fin de Class

Conclusion :


Permet de regrouper plusieurs extractions en un seul fichier Excel multi onglet.
De mettre en forme les tableaux. L'utilisation du format conditionnel est possible.
Le fichier Excel passé en paramètre peut être un fichier "modèle" car il n'est pas écrit puisque c'est une copie que l'on fait...

Nécessite l'API Excel jxl.jar et une autre librairie : Fichier.zip

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.