How to read and write excel file

后端 未结 22 2579
北荒
北荒 2020-11-22 04:49

I want to read and write an Excel file from Java with 3 columns and N rows, printing one string in each cell. Can anyone give me simple code snippet for this? Do I need to

相关标签:
22条回答
  • 2020-11-22 05:02

    A simple CSV file should suffice

    0 讨论(0)
  • 2020-11-22 05:02

    You can not read & write same file in parallel(Read-write lock). But, we can do parallel operations on temporary data(i.e. Input/output stream). Write the data to file only after closing the input stream. Below steps should be followed.

    • Open the file to Input stream
    • Open the same file to an Output Stream
    • Read and do the processing
    • Write contents to output stream.
    • Close the read/input stream, close file
    • Close output stream, close file.

    Apache POI - read/write same excel example

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.sql.Date;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;
    
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    
    public class XLSXReaderWriter {
    
        public static void main(String[] args) {
    
            try {
                File excel = new File("D://raju.xlsx");
                FileInputStream fis = new FileInputStream(excel);
                XSSFWorkbook book = new XSSFWorkbook(fis);
                XSSFSheet sheet = book.getSheetAt(0);
    
                Iterator<Row> itr = sheet.iterator();
    
                // Iterating over Excel file in Java
                while (itr.hasNext()) {
                    Row row = itr.next();
    
                    // Iterating over each column of Excel file
                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
    
                        Cell cell = cellIterator.next();
    
                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        default:
    
                        }
                    }
                    System.out.println("");
                }
    
                // writing data into XLSX file
                Map<String, Object[]> newData = new HashMap<String, Object[]>();
                newData.put("1", new Object[] { 1d, "Raju", "75K", "dev",
                        "SGD" });
                newData.put("2", new Object[] { 2d, "Ramesh", "58K", "test",
                        "USD" });
                newData.put("3", new Object[] { 3d, "Ravi", "90K", "PMO",
                        "INR" });
    
                Set<String> newRows = newData.keySet();
                int rownum = sheet.getLastRowNum();
    
                for (String key : newRows) {
                    Row row = sheet.createRow(rownum++);
                    Object[] objArr = newData.get(key);
                    int cellnum = 0;
                    for (Object obj : objArr) {
                        Cell cell = row.createCell(cellnum++);
                        if (obj instanceof String) {
                            cell.setCellValue((String) obj);
                        } else if (obj instanceof Boolean) {
                            cell.setCellValue((Boolean) obj);
                        } else if (obj instanceof Date) {
                            cell.setCellValue((Date) obj);
                        } else if (obj instanceof Double) {
                            cell.setCellValue((Double) obj);
                        }
                    }
                }
    
                // open an OutputStream to save written data into Excel file
                FileOutputStream os = new FileOutputStream(excel);
                book.write(os);
                System.out.println("Writing on Excel file Finished ...");
    
                // Close workbook, OutputStream and Excel file to prevent leak
                os.close();
                book.close();
                fis.close();
    
            } catch (FileNotFoundException fe) {
                fe.printStackTrace();
            } catch (IOException ie) {
                ie.printStackTrace();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:08

    I edited the most voted one a little cuz it didn't count blanks columns or rows well not totally, so here is my code i tested it and now can get any cell in any part of an excel file. also now u can have blanks columns between filled column and it will read them

      try {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir));
    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;
    int cblacks=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;else{rows++;cblacks++;}
        }
    
        cols++;
    }
    cols=cols+cblacks;
    for(int r = 0; r < rows; r++) {
        row = sheet.getRow(r);
        if(row != null) {
            for(int c = 0; c < cols; c++) {
                cell = row.getCell(c);
                if(cell != null) {
                    System.out.print(cell+"\n");//Your Code here
                }
            }
        }
    }} catch(Exception ioe) {
    ioe.printStackTrace();}
    
    0 讨论(0)
  • 2020-11-22 05:10

    When using the apache poi 4.1.2. The celltype changes a bit. Below is an example

        try {
            File excel = new File("/home/name/Downloads/bb.xlsx");
            FileInputStream fis = new FileInputStream(excel);
            XSSFWorkbook book = new XSSFWorkbook(fis);
            XSSFSheet sheet = book.getSheetAt(0);
    
            Iterator<Row> itr = sheet.iterator();
    
            // Iterating over Excel file in Java
            while (itr.hasNext()) {
                Row row = itr.next();
    
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
    
    
    
                    Cell cell = cellIterator.next();
    
    
    
                    switch (cell.getCellType()) {
                    case STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                    case BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + "\t");
                        break;
                    default:
    
    
                    }
                }
                System.out.println("");}
            }catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
    
    0 讨论(0)
  • 2020-11-22 05:13

    Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.

    Import data

    try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
      rowStream
        // skip the header row that contains the column names
        .skip(1)
        .forEach(row -> {
          System.out.println(
            "row n°" + row.rowIndex()
            + " column 'User login' value : " + row.cell("User login").asString()
            + " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
          );
        });
    }
    

    Export data

    Windmill
      .export(Arrays.asList(bean1, bean2, bean3))
      .withHeaderMapping(
        new ExportHeaderMapping<Bean>()
          .add("Name", Bean::getName)
          .add("User login", bean -> bean.getUser().getLogin())
      )
      .asExcel()
      .writeTo(new FileOutputStream("Export.xlsx"));
    
    0 讨论(0)
  • 2020-11-22 05:14

    If column number are varing you can use this

    package com.org.tests;
    import org.apache.poi.xssf.usermodel.*;
    import java.io.FileInputStream;
    import java.io.IOException;
    
    public class ExcelSimpleTest 
    {   
        String path;
        public FileInputStream fis = null;
        private XSSFWorkbook workbook = null;
        private XSSFSheet sheet = null;
        private XSSFRow row   =null;
        private XSSFCell cell = null;
    
        public ExcelSimpleTest() throws IOException
        {
            path = System.getProperty("user.dir")+"\\resources\\Book1.xlsx";
            fis = new FileInputStream(path); 
            workbook = new XSSFWorkbook(fis);
            sheet = workbook.getSheetAt(0);
        }
        public void ExelWorks()
        {
            int index = workbook.getSheetIndex("Sheet1");
            sheet = workbook.getSheetAt(index);
            int rownumber=sheet.getLastRowNum()+1;  
    
            for (int i=1; i<rownumber; i++ )
            {
                row = sheet.getRow(i);
                int colnumber = row.getLastCellNum();
                for (int j=0; j<colnumber; j++ )
                {
                    cell = row.getCell(j);
                    System.out.println(cell.getStringCellValue());
                }
            }
        }   
        public static void main(String[] args) throws IOException 
        {
            ExcelSimpleTest excelwork = new ExcelSimpleTest();
            excelwork.ExelWorks();
        }
    }
    

    The corresponding mavendependency can be found here

    0 讨论(0)
提交回复
热议问题