How to read and write excel file

后端 未结 22 2578
北荒
北荒 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:16

    First add all these jar files in your project class path:

    1. poi-scratchpad-3.7-20101029
    2. poi-3.2-FINAL-20081019
    3. poi-3.7-20101029
    4. poi-examples-3.7-20101029
    5. poi-ooxml-3.7-20101029
    6. poi-ooxml-schemas-3.7-20101029
    7. xmlbeans-2.3.0
    8. dom4j-1.6.1

    Code for writing in a excel file:

    public static void main(String[] args) {
        //Blank workbook
        XSSFWorkbook workbook = new XSSFWorkbook();
    
        //Create a blank sheet
        XSSFSheet sheet = workbook.createSheet("Employee Data");
    
        //This data needs to be written (Object[])
        Map<String, Object[]> data = new TreeMap<String, Object[]>();
        data.put("1", new Object[]{"ID", "NAME", "LASTNAME"});
        data.put("2", new Object[]{1, "Amit", "Shukla"});
        data.put("3", new Object[]{2, "Lokesh", "Gupta"});
        data.put("4", new Object[]{3, "John", "Adwards"});
        data.put("5", new Object[]{4, "Brian", "Schultz"});
    
        //Iterate over data and write to sheet
        Set<String> keyset = data.keySet();
    
        int rownum = 0;
        for (String key : keyset) 
        {
            //create a row of excelsheet
            Row row = sheet.createRow(rownum++);
    
            //get object array of prerticuler key
            Object[] objArr = data.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 Integer) 
                {
                    cell.setCellValue((Integer) obj);
                }
            }
        }
        try 
        {
            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
            workbook.write(out);
            out.close();
            System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    

    Code for reading from excel file

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    
    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
    
            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(file);
    
            //Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);
    
            //Iterate through each rows one by one
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext())
            {
                Row row = rowIterator.next();
                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();
    
                while (cellIterator.hasNext()) 
                {
                    Cell cell = cellIterator.next();
                    //Check the cell type and format accordingly
                    switch (cell.getCellType()) 
                    {
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");
                            break;
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                    }
                }
                System.out.println("");
            }
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:16

    If you go for third party library option, try using Aspose.Cells API that enables Java Applications to create (read/write) and manage Excel spreadsheets efficiently without requiring Microsoft Excel.

    e.g

    Sample code:

    1.

    //Load sample workbook
    Workbook wb = new Workbook(dirPath + "sample.xlsx");
    
    //Access first worksheet
    Worksheet ws = wb.getWorksheets().get(0);
    
    //Access cells iterator
    Iterator itrat = ws.getCells().iterator();
    
    //Print cells name in iterator
    while(itrat.hasNext())
    {
        Cell cell = (Cell)itrat.next();
    
        System.out.println(cell.getName() + ": " + cell.getStringValue().trim());
    }
    
    Workbook book = new Workbook("sample.xlsx");
    Worksheet sheet = book.getWorksheets().get(0);
    Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
    Iterator rangeIterator = range.iterator();
    while(rangeIterator.hasNext())
    {
    Cell cell = (Cell)rangeIterator.next();
    //your code goes here.
    }
    

    Hope, this helps a bit.

    PS. I am working as Support developer/ Evangelist at Aspose.

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

    Apache POI can do this for you. Specifically the HSSF module. The quick guide is most useful. Here's how to do what you want - specifically create a sheet and write it out.

    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();
    
    0 讨论(0)
  • 2020-11-22 05:17

    If you need to do anything more with office documents in Java, go for POI as mentioned.

    For simple reading/writing an excel document like you requested, you can use the CSV format (also as mentioned):

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    
    public class CsvWriter {
     public static void main(String args[]) throws IOException {
    
      String fileName = "test.xls";
    
      PrintWriter out = new PrintWriter(new FileWriter(fileName));
      out.println("a,b,c,d");
      out.println("e,f,g,h");
      out.println("i,j,k,l");
      out.close();
    
      BufferedReader in = new BufferedReader(new FileReader(fileName));
      String line = null;
      while ((line = in.readLine()) != null) {
    
       Scanner scanner = new Scanner(line);
       String sep = "";
       while (scanner.hasNext()) {
        System.out.println(sep + scanner.next());
        sep = ",";
       }
      }
      in.close();
     }
    }
    
    0 讨论(0)
提交回复
热议问题