Wie man eine Excel-Datei liest und schreibt

Ich möchte eine Excel-Datei mit 3 Spalten und N Zeilen aus Java lesen und schreiben, wobei in jede Zelle eine Zeichenfolge gedruckt wird. Kann mir jemand einen einfachen Codeschnipsel dafür geben? Muss ich eine externe Bibliothek verwenden oder hat Java eine eingebaute Unterstützung dafür?

Ich möchte das Folgende tun:

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]

Versuchen Sie das Apache POI HSSF. Hier ist ein Beispiel, wie man eine Excel-Datei liest:

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();
}

Auf der Dokumentationsseite finden Sie auch Beispiele dafür, wie man in Excel-Dateien schreiben kann.

Kommentare (6)

Der Apache POI kann dies für Sie tun. Insbesondere das HSSF Modul. Die Kurzanleitung ist sehr nützlich. Hier sehen Sie, wie Sie das machen, was Sie wollen - nämlich ein Blatt erstellen und es ausschreiben.

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();
Kommentare (0)

Eine einfache CSV-Datei sollte ausreichen

Kommentare (6)