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
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
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
jxl et java eclipse [ par sofia2007 ]
salut tout le monde j'ai un tableur ds mon programme je veux le sauvegarder dans un fichier excel alors j'ai téléchargé JExcelApi v2.6.12 (1911kbytes)
Pb encoding avec JXL sur UNIX [ par Mirdhynn ]
Bonjour J'essaie actuellement d'utiliser le package Jxl pour manipuler des fichier Excel. Aprés avoir créé ma clase et l'avoir testée avec succés su
importer d un fichier excel dans une base de données mysql [ par intel42 ]
bonjour, je suis débutante en java.Il m'a été demandé d'importer un fichier excel dans une base de données mysql. J'utilise des javabeans pour faire l
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
|
Derniers Blogs
GESTION D'EXCEPTION AVEC LES TASKSGESTION D'EXCEPTION AVEC LES TASKS par richardc
Nous avons vu dans un précédent article comment utiliser Task pour effectuer des opérations dans un autre thread.
Malheureusement, comme tout le monde n'est pas parfait, il se peut que cette exécution se passe mal et qu'une exception se produise.
La...
Cliquez pour lire la suite de l'article par richardc DéMARRONS AVEC LES TASKSDéMARRONS AVEC LES TASKS par richardc
Que vous le vouliez ou non, le développement multi-tâche est maintenant une obligation pour toute nouvelle application. Il est donc vital d'en comprendre les mécanismes et de s'y mettre le plus tôt possible.
En attendant le .NET Framework 4.5 avec le...
Cliquez pour lire la suite de l'article par richardc SLIDE & DéMO TECHDAYS 2012 - FAST & FURIOUS XAML APPSSLIDE & DéMO TECHDAYS 2012 - FAST & FURIOUS XAML APPS par Vko
Retrouvez les slides et les démo de ma session Fast & Furious XAML Apps. A ceux qui se posent la question : "est-ce que le code de la DataGrid est disponible?", je vous répondrais "pas encore". Je vais mettre en place un projet codeplex pour part...
Cliquez pour lire la suite de l'article par Vko XNA IS DEAD!XNA IS DEAD! par richardc
Depuis la semaine dernière (et grâce aux TechDays 2012), je me penche activement sur la nouvelle version de Windows, aka Windows 8. Vous me direz, il était temps puisque la première preview date de Septembre dernier.
OK. Remarquez, on n'en est qu'aux...
Cliquez pour lire la suite de l'article par richardc TECHDAYS PARIS 2012 : WINDOWS SERVER "8" QUOI DE 9 !TECHDAYS PARIS 2012 : WINDOWS SERVER "8" QUOI DE 9 ! par ROMELARD Fabrice
Speakers: Fabrice Meillon et Stanislas Quastana Cette session est basée entièrement sur celle donnée lors de la BUILD cet hiver. Il n'y a pas d'ajout d'information en rapport avec cet évènement passé. Windows 8 Server sera intégralem...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Forum
RE : COURRE : COUR par mamadokhalid
Cliquez pour lire la suite par mamadokhalid
Logiciels
DocTranslate (V3.1.0.0)DOCTRANSLATE (V3.1.0.0)DocTranslate est un traducteur de document Microsoft Word, PowerPoint et Excel. Il permet d'autom... Cliquez pour télécharger DocTranslate Tribler (2012)TRIBLER (2012)Tribler est un client pair à pair (P2P/Peer-to-Peer) open source avec la capacité de regarder des... Cliquez pour télécharger Tribler OneSwarm (2012)ONESWARM (2012)Le peer-to-peer qui protège votre vie privée, c'est OneSwarm.
Ce logiciel de peer-to-peer crypté... Cliquez pour télécharger OneSwarm PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V8.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V8.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System
|