1
我想創建一個循環來新表添加到工作簿,但下面的代碼無法正常工作。爲什麼循環會覆蓋初始代碼,而不是創建新的XSSFSheet?
它創建了一個新的工作表,但只是覆蓋了第一個表,而不是添加一個新的。
我認爲它可能有一些做的FILEOUT流,但添加fileOut.close()
到最後也沒解決問題。
public static void main (String[] args) throws IOException
{
String response;
XSSFWorkbook workbook;
do
{
// prompts user to pick file
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File("C:\\Users\\AMDX12\\Desktop"));
fc.setDialogTitle("Choose File");
fc.showOpenDialog(null);
File selectedFile = fc.getSelectedFile();
// gets questionPacketNumber from user
System.out.println("Enter the number of the question packet: ");
Scanner keyboard = new Scanner (System.in);
String questionPacketNum = keyboard.nextLine();
// creates new Workbook and a new Sheet
workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(questionPacketNum);
// loops code
System.out.println("would you like to do this again?");
response = keyboard.nextLine();
// saves workbook
FileOutputStream fileOut = new FileOutputStream (new File ("c:\\Users\\Student\\newFile.xlsx"));
workbook.write(fileOut);
// fileOut.close();
} while (response.equalsIgnoreCase("yes") == true);
}
我跟你說什麼,它解決了這一問題。感謝您提到單一責任原則。 –