How to read and write excel file

后端 未结 22 2996
北荒
北荒 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: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();
     }
    }
    

提交回复
热议问题