Ako čítať a zapisovať súbor Excel

Chcem čítať a zapisovať súbor programu Excel z jazyka Java s 3 stĺpcami a N riadkami, pričom v každej bunke vypíšem jeden reťazec. Môže mi niekto poskytnúť jednoduchý úryvok kódu na tento účel? Musím použiť nejakú externú lib alebo má Java pre to zabudovanú podporu?

Chcem urobiť nasledovné:

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]

Skúste Apache POI HSSF. Tu'je príklad, ako čítať súbor 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();
}

Na stránke dokumentácie máte aj príklady, ako zapisovať do súborov excel.

Komentáre (6)

Apache POI to môže urobiť za vás. Konkrétne modul HSSF. Najužitočnejší je rýchly sprievodca. Tu'je návod, ako urobiť to, čo chcete - konkrétne vytvoriť hárok a vypísať ho.

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();
Komentáre (0)

Mal by stačiť jednoduchý súbor CSV

Komentáre (6)