Je veux lire et écrire un fichier Excel à partir de Java avec 3 colonnes et N lignes, en imprimant une chaîne dans chaque cellule. Quelqu'un peut-il me donner un extrait de code simple pour cela ? Dois-je utiliser une librairie externe ou Java a-t-il un support intégré pour cela ?
Je veux faire ce qui suit :
for(i=0; i <rows; i++)
//read [i,col1] ,[i,col2], [i,col3]
for(i=0; i<rows; i++)
//write [i,col1], [i,col2], [i,col3]
Essayez le [Apache POI HSSF][1]. Voici un exemple de lecture d'un fichier Excel :
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell((short)c);
if(cell != null) {
// Your code here
}
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}
Sur la page de documentation, vous trouverez également des exemples sur la façon d'écrire dans des fichiers Excel.
[1] : https://poi.apache.org/
Le module [Apache POI][1] peut le faire pour vous. Plus précisément, le module [HSSF][2]. Le [guide rapide][3] est très utile. Voici comment faire ce que vous voulez - en particulier créer une feuille et l'écrire.
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
[1] : http://poi.apache.org/ [2] : http://poi.apache.org/spreadsheet/index.html [3] : http://poi.apache.org/spreadsheet/quick-guide.html