How to fill in Excel file using java

前端 未结 8 2217
离开以前
离开以前 2021-01-05 05:08

I have the following code to fill in the Excel file, with information that I get from the Internet using Jsoup.

package knvbj;

import java.io.FileInputStrea         


        
8条回答
  •  情深已故
    2021-01-05 05:40

    The problem lies in your FileOutputStream variable out being used more than once for the same Workbook. Opening and closing the FileOutputStream out within the loop fix your exception. POI, and/or the xml/zip library, don't like to use the same stream more than once.

    If you use the same code you had with 1 loop, it works, with 2, it will crashes with the exception you have.

    Here's a quick fix with a simple code to replace what the JSoup code did :

      private static int Clnummer = 1;
    
      public static void main(String[] args) throws IOException {
        for (int i = 0; i < 2; i++) {
          FileOutputStream out = new FileOutputStream("yourfilePath");
          String NameOfClub = "Potaoes club";
          System.out.println(NameOfClub);
    
          String PlaatsName;
          String Straat;
          String telNo;
          String Accommodatie;
          String Postcode;
    
          Accommodatie = "123";
          Straat = "Potatoes club street";
          telNo = "123456789";
    
          Postcode = "P0P0P0";
          PlaatsName = "PotatoCity";
    
          String email = "potatoKing@potato.com";
    
          String fname = "guessing this is a template file";
          InputStream inp = new FileInputStream(fname);                       
    
          Workbook wb = new XSSFWorkbook(inp);
    
          Sheet sheet = wb.getSheetAt(0);
          Row r1 = sheet.getRow(0);
    
          r1.createCell(Clnummer++).setCellValue(NameOfClub);
          r1.createCell(Clnummer++).setCellValue(Accommodatie);
          r1.createCell(Clnummer++).setCellValue(Straat);
          r1.createCell(Clnummer++).setCellValue(Postcode);
          r1.createCell(Clnummer++).setCellValue(PlaatsName);
          r1.createCell(Clnummer++).setCellValue(telNo);
          r1.createCell(Clnummer++).setCellValue(email);
    
          wb.write(out);
          out.close();
        }
      }
    }
    

提交回复
热议问题