Accueil > > > CVT_XLS // PERMET DE CONVERTIR UN FICHIER CSV EN FICHIER EXCEL
CVT_XLS // PERMET DE CONVERTIR UN FICHIER CSV EN FICHIER EXCEL
Information sur la source
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
- //=======================================================================
- // 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’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’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
//=======================================================================
// 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’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’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
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
excel [ par ptit pimousse ]
j'ai une erreur que je ne comprends pas lors de la creation d'un workbookvoilà le code://là ca marchejava.io.File fichier = new java.io.File(chemin);/
[JXL] Extraire une worksheet d'un fichier.xls vers une JTable [ par nicolason13 ]
Bonjour, Je cherche à extraire le contenu d'une worksheet Excel vers une JTable en utilisant l'API JXL. Je sais que celle-ci permet de lire et ecrire
transfer d'un fichier excel en un fichier .csv [ par elbakkaliabderrahim ]
bonjour tout le mondej'ai besoin de transferer un fichier excel en un fichier .csv mais je n'en ai aucune ideeveuiller aider moi.et merci
Lire dans un excel [ par rocky_jr ]
Bonjour, j'ai un petit problème en Java. Je voudrais lire dans un fichier Excel pour y extraire des données et les traiter dans un programme
modifié le contenu le contenu d'un fichier EXCEL en utilisant JEXCEL API [ par info20072008 ]
bonjour,j'utilise JEXCEL API pour manipuler des fichier EXCEL je recupère un fichier EXCEL que j'ai bien organisé et je veux le remplir pour cela : j
jxl [ par munisys ]
bonjour tt le monde,c'est ma deuxième demande.bon j ai pas eu la réponse que je voulais. donc j attends de vous plus de détails svp ..:
Lecture fichier Excel avec JExcelAPI [ par tatou42 ]
Bonjour, Je souhaite lire un fichier Excel en utilisant JExcelAPI. Dans mon code source j'aiimport jxl.*;...File excelFile;...try{Workbook worbook = W
Récupération de valeurs dans un fichier csv [ par Bloodyhell ]
J'ai crée une JTextArea. Le texte qui j'insert dedans est stocké, après validation, dans une bdd MySQL. Je récupère ensuite c
Générer un graphique excel [ par ptitlatino ]
Bonjour,Je voudrais savoir si qqun connait le moyen de créer un cammenbert sur excel à partir de certaines connées. Je ne connais pas t
[JTable] changer de couleur de texte pour une ligne [ par Bloodyhell ]
Bonjour,J'ai crée une JTable qui est alimentée par un fichier csv. J'ai 2 colonnes et le nombre de ligne est variable. Ce que je souhaiterai
|
Derniers Blogs
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|