How to read and write excel file

后端 未结 22 2608
北荒
北荒 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 04:51

    You need Apache POI library and this code below should help you

        import java.io.File;
        import java.io.FileInputStream;
        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.util.ArrayList;
        import java.util.List;
        import java.util.Iterator;
        //*************************************************************
        import org.apache.poi.ss.usermodel.Sheet;
        import org.apache.poi.ss.usermodel.Cell;
        import org.apache.poi.ss.usermodel.Row;
        import org.apache.poi.ss.usermodel.Workbook;
        import org.apache.poi.xssf.usermodel.XSSFSheet;
        import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
        //*************************************************************
       public class AdvUse {
    
        private static Workbook wb ; 
        private static Sheet sh ; 
        private static FileInputStream fis ; 
        private static FileOutputStream fos  ; 
        private static Row row  ; 
        private static Cell cell  ;
        private static String ExcelPath ; 
    
        //*************************************************************
        public static void setEcxelFile(String ExcelPath, String SheetName) throws Exception {
        try {
       File f= new File(ExcelPath); 
       if(!f.exists()){
           f.createNewFile();
           System.out.println("File not Found so created");
       }
    
        fis = new FileInputStream("./testData.xlsx");
        wb = WorkbookFactory.create(fis); 
        sh = wb.getSheet("SheetName");
        if(sh == null){
            sh = wb.getSheet(SheetName); 
        }
        }catch(Exception e)
        {System.out.println(e.getMessage());
        }
        }
    
          //*************************************************************
          public static void setCellData(String text , int rowno , int colno){
        try{
            row = sh.getRow(rowno);
            if(row == null){
                row = sh.createRow(rowno);
            }
            cell = row.getCell(colno);
            if(cell!=null){
                cell.setCellValue(text);
    
            }
            else{
                cell = row.createCell(colno);
                cell.setCellValue(text);
    
            }
            fos = new FileOutputStream(ExcelPath);
            wb.write(fos);
            fos.flush();
            fos.close();
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
        }
    
          //*************************************************************
          public static String getCellData(int rowno , int colno){
            try{
    
                cell = sh.getRow(rowno).getCell(colno); 
                String CellData = null ;
                switch(cell.getCellType()){
                case  STRING :
                    CellData = cell.getStringCellValue();
                   break ; 
                case NUMERIC : 
                    CellData = Double.toString(cell.getNumericCellValue());
                    if(CellData.contains(".o")){
                        CellData = CellData.substring(0,CellData.length()-2);
    
                    }
                break ; 
                case BLANK : 
                CellData = ""; break ; 
    
                }
                return CellData;
            }catch(Exception e){return ""; }
        }
    
           //*************************************************************
          public static int getLastRow(){
            return sh.getLastRowNum();
        }
    
    0 讨论(0)
  • 2020-11-22 04:52

    There is a new easy and very cool tool (10x to Kfir): xcelite

    Write:

    public class User { 
    
      @Column (name="Firstname")
      private String firstName;
    
      @Column (name="Lastname")
      private String lastName;
    
      @Column
      private long id; 
    
      @Column
      private Date birthDate; 
    }
    
    Xcelite xcelite = new Xcelite();    
    XceliteSheet sheet = xcelite.createSheet("users");
    SheetWriter<User> writer = sheet.getBeanWriter(User.class);
    List<User> users = new ArrayList<User>();
    // ...fill up users
    writer.write(users); 
    xcelite.write(new File("users_doc.xlsx"));
    

    Read:

    Xcelite xcelite = new Xcelite(new File("users_doc.xlsx"));
    XceliteSheet sheet = xcelite.getSheet("users");
    SheetReader<User> reader = sheet.getBeanReader(User.class);
    Collection<User> users = reader.read();
    
    0 讨论(0)
  • 2020-11-22 04:53

    Sure , you will find the code below useful and easy to read and write. This is a util class which you can use in your main method and then you are good to use all methods below.

         public class ExcelUtils {
         private static XSSFSheet ExcelWSheet;
         private static XSSFWorkbook ExcelWBook;
         private static XSSFCell Cell;
         private static XSSFRow Row;
         File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
         public void setExcelFile(File Path, String SheetName) throws Exception                
    
        try {
            FileInputStream ExcelFile = new FileInputStream(Path);
            ExcelWBook = new XSSFWorkbook(ExcelFile);
            ExcelWSheet = ExcelWBook.getSheet(SheetName);
        } catch (Exception e) {
            throw (e);
        }
    
    }
    
    
          public static String getCellData(int RowNum, int ColNum) throws Exception {
    
        try {
            Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
            String CellData = Cell.getStringCellValue();
            return CellData;
        } catch (Exception e) {
    
            return "";
    
        }
    
    }
    public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {
    
        try {
            Row = ExcelWSheet.createRow(RowNum - 1);
            Cell = Row.createCell(ColNum - 1);
            Cell.setCellValue(Result);
            FileOutputStream fileOut = new FileOutputStream(Path);
            ExcelWBook.write(fileOut);
            fileOut.flush();
            fileOut.close();
        } catch (Exception e) {
    
            throw (e);
    
        }
    
    }
    
    }
    
    0 讨论(0)
  • 2020-11-22 04:53

    This will write a JTable to a tab separated file that can be easily imported into Excel. This works.

    If you save an Excel worksheet as an XML document you could also build the XML file for EXCEL with code. I have done this with word so you do not have to use third-party packages.

    This could code have the JTable taken out and then just write a tab separated to any text file and then import into Excel. I hope this helps.

    Code:

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import javax.swing.JTable;
    import javax.swing.table.TableModel;
    
    public class excel {
        String columnNames[] = { "Column 1", "Column 2", "Column 3" };
    
        // Create some data
        String dataValues[][] =
        {
            { "12", "234", "67" },
            { "-123", "43", "853" },
            { "93", "89.2", "109" },
            { "279", "9033", "3092" }
        };
    
        JTable table;
    
        excel() {
            table = new JTable( dataValues, columnNames );
        }
    
    
        public void toExcel(JTable table, File file){
            try{
                TableModel model = table.getModel();
                FileWriter excel = new FileWriter(file);
    
                for(int i = 0; i < model.getColumnCount(); i++){
                    excel.write(model.getColumnName(i) + "\t");
                }
    
                excel.write("\n");
    
                for(int i=0; i< model.getRowCount(); i++) {
                    for(int j=0; j < model.getColumnCount(); j++) {
                        excel.write(model.getValueAt(i,j).toString()+"\t");
                    }
                    excel.write("\n");
                }
    
                excel.close();
    
            }catch(IOException e){ System.out.println(e); }
        }
    
        public static void main(String[] o) {
            excel cv = new excel();
            cv.toExcel(cv.table,new File("C:\\Users\\itpr13266\\Desktop\\cs.tbv"));
        }
    }
    
    0 讨论(0)
  • 2020-11-22 04:54

    Try the Apache POI HSSF. Here's an example on how to read an excel file:

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

    On the documentation page you also have examples of how to write to excel files.

    0 讨论(0)
  • 2020-11-22 04:56

    .csv or POI will certainly do it, but you should be aware of Andy Khan's JExcel. I think it's by far the best Java library for working with Excel there is.

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