Java 将用户输入获取到excel(Apache poi)

Java 将用户输入获取到excel(Apache poi),java,excel,apache,Java,Excel,Apache,我正在尝试使用apache将用户输入的信息输入excel电子表格,以便保存他们的帐户信息。如何将他们的用户名和密码输入到本文档中,以便每个用户名和密码组合都有自己的行?以下是我目前的代码: 创建图纸: import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.s

我正在尝试使用apache将用户输入的信息输入excel电子表格,以便保存他们的帐户信息。如何将他们的用户名和密码输入到本文档中,以便每个用户名和密码组合都有自己的行?以下是我目前的代码:

创建图纸:

import java.io.FileOutputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;


public class Spreadsheet {

    public Spreadsheet() {
        Workbook AccountInfo = new HSSFWorkbook();
        Sheet Information = AccountInfo.createSheet();

        Row titles = Information.createRow(0);

        Cell username = titles.createCell(0);
        username.setCellValue("Username");

        Cell password = titles.createCell(1);
        password.setCellValue("Password");

        try {
            FileOutputStream Accounts = new FileOutputStream("Account Information.xls");
            AccountInfo.write(Accounts);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
获取用户输入:

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.Border;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class CreateAccount extends JFrame implements ActionListener {

    Workbook AccountInfo = new HSSFWorkbook();
    Sheet Information = AccountInfo.createSheet();

    JLabel username = new JLabel("Enter your username");
    JTextField enterUsername = new JTextField(null, 15);
    JLabel password = new JLabel("Enter your password");
    JPasswordField enterPassword = new JPasswordField(null, 15);
    JLabel passwordConfirm = new JLabel("Confirm your password.");
    JPasswordField enterConfirmPassword = new JPasswordField(null, 15);
    JButton okButton = new JButton("OK");

    String userName;
    double balance;
    String passString;

    public CreateAccount() {

        add(username);
        add(enterUsername);
        add(password);
        add(enterPassword);
        add(passwordConfirm);
        add(enterConfirmPassword);
        add(okButton);

        okButton.addActionListener(this);

        setTitle("New Bank Account Creation");
        setVisible(true);
        setLocationRelativeTo(null);
        setSize(270, 250);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

    }

    @Override
    public void actionPerformed(ActionEvent e) {

        char[] pass = enterPassword.getPassword();
        passString = new String(pass);

        char[] passConfirm = enterConfirmPassword.getPassword();
        String passStringConfirm = new String(passConfirm);

        userName = enterUsername.getText();

        if (e.getSource() == okButton) {
            if(userName.isEmpty() || passString.isEmpty() || !passString.equals(passStringConfirm)) {

                    enterUsername.setText("");
                    enterPassword.setText("");
                    enterConfirmPassword.setText("");
                    Border redLine = BorderFactory.createLineBorder(Color.red);
                    enterUsername.setBorder(redLine);
                    enterPassword.setBorder(redLine);
                    enterConfirmPassword.setBorder(redLine);
                    }
            }if(!userName.isEmpty() && !passString.isEmpty() && passString.equals(passStringConfirm)){
                    addAccount(userName,passString);

                super.dispose();

            int response = 0;
            String firstDesposit = JOptionPane.showInputDialog("Welcome " + userName + ". Enter your initial deposit.\n" + "If you wouldn't like to make an initial deposit, press CANCEL.");
            balance = Double.parseDouble(firstDesposit);
            if (response == JOptionPane.OK_OPTION) {
                new Menu();
                }
            }   
        }
    private void addAccount(String username, String password) throws IOException {

        FileInputStream file = new FileInputStream(new File("Account Information.xls"));           
        HSSFWorkbook workbook = new HSSFWorkbook(file); 
        HSSFSheet sheet = workbook.getSheetAt(0);

        int newRowIndex = sheet.getPhysicalNumberOfRows(); //index of new row to create
        HSSFRow newRow = sheet.getRow(newRowIndex);

        HSSFCell usernameCell = newRow.createCell(0);
        usernameCell.setCellValue(username);
        HSSFCell passwordCell = newRow.createCell(1);
        passwordCell.setCellValue(password);
    }
}
下面是我试图实现confirmUsername()方法的类

导入java.awt.Dimension;
导入java.awt.FlowLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.util.Iterator;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JTextField;
导入org.apache.poi.ss.usermodel.Cell;
导入org.apache.poi.ss.usermodel.Row;
公共类ViewAccount扩展JFrame实现ActionListener{
AccountSpreadsheet电子表格=新的AccountSpreadsheet();
JLabel用户名=新的JLabel(“用户名:”);
JTextField enterUserName=新的JTextField(null,15);
JLabel Password=新的JLabel(“密码:”);
JTextField enterPassword=新的JTextField(null,15);
JButton log=新JButton(“登录”);
账户;
公共视图帐户(){
添加(用户名);
添加(输入用户名);
添加(密码);
添加(输入密码);
添加(日志);
log.setPreferredSize(新维度(250,40));
log.addActionListener(this);
设置标题(“登录”);
setVisible(真);
设置大小(300150);
setLayout(新的FlowLayout());
setLocationRelativeTo(空);
setDefaultCloseOperation(关闭时退出);
}
@凌驾
已执行的公共无效操作(操作事件e){
如果(例如getSource()==log){
confirmUsername();
}
}
公共void confirmUsername(){
AccountSpreadsheet电子表格=新的AccountSpreadsheet();
CreateCount Acct=新建CreateCount();
String passString=Acct.passString;
字符串userName=Acct.userName;
for(迭代器rit=Spreadsheet.sheet.rowIterator();rit.hasNext();){
Row=rit.next();
for(迭代器cit=row.cellIterator();cit.hasNext();){
Cell Cell=cit.next();
字符串名称=cell.getStringCellValue();
如果(用户名==名称){
引文next();
if(passString==name){
System.out.println(“日志成功”);
}否则{
System.out.println(“错误”);
}
}否则{
System.out.println(“错误”);
}
}
}
}
}

我知道调用CreateAccount只会使CreateAccount构造函数中的另一个窗口弹出,但我不确定如何将用户名和密码字符串输入到方法中。

电子表格的代码不应运行多次。这样做将删除您存储的任何信息。这是一个很好的电子表格类

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

public class AccountSpreadsheet {

    private XSSFSheet sheet;
    private final String filename = "Account Information.xlsx";

    public AccountSpreadsheet() {
        try {
            FileInputStream file = new FileInputStream(new File(filename));
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            sheet = workbook.getSheetAt(0);
        } catch (FileNotFoundException e) {
            createSpreadsheet(); //file didn't exist yet
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void createSpreadsheet() {
        XSSFWorkbook workbook = new XSSFWorkbook();
        sheet = workbook.createSheet();
        XSSFRow row = sheet.createRow(0);
        XSSFCell username = row.createCell(0);
        username.setCellValue("Username");
        XSSFCell password = row.createCell(1);
        password.setCellValue("Password");
        save();
    }

    public void addAccount(String username, String password) {
        int newRowIndex = sheet.getPhysicalNumberOfRows();
        XSSFRow newRow = sheet.createRow(newRowIndex);

        XSSFCell usernameCell = newRow.createCell(0);
        usernameCell.setCellValue(username);
        XSSFCell passwordCell = newRow.createCell(1);
        passwordCell.setCellValue(password);
        save();
    }

    private void save() {
        try {
            FileOutputStream outStream = new FileOutputStream(filename);
            sheet.getWorkbook().write(outStream);
            outStream.close();
            sheet = new XSSFWorkbook(new FileInputStream(new File(filename))).getSheetAt(0); //POI bug requires this
        }catch(Exception e){
            e.printStackTrace();
        }
    }

//    public boolean accountExists(String username){
//        //does account exist?
//    }
//
//    public boolean correctLogin(String username, String password) {
//        //correct username and password?
//    }
}

在CreateAccount类中拥有AccountSpreadsheet实例,并调用addAccount(用户名、密码)验证后。

问题是您不确定已填充了多少行,因此您不确定在何处创建新的行?@yts我不确定如何获取用户输入的用户名和密码,并将其放入创建的excel电子表格的“用户名”和“密码”列中。我想将用户名和密码输入此电子表格,以便稍后允许用户登录进行存款和取款。我正在寻找答案,但您确定要这样做吗?数据库更适合于此。@很遗憾,我的AP计算机科学课程分配仅限于使用apache进行此操作。验证登录的方法是什么样的?我尝试使用迭代器遍历列表,直到它找到输入的用户名(如果它与输入的用户名匹配),然后调用cell.next()查看密码是否是分配给用户名的密码,但无法使其正常工作。有什么问题?发布一个关于代码和问题的问题,并在这里给我链接,我来看看。我不能保证我在这里给出的答案是完整的,但我会尽力为您指出正确的方向;)添加了ViewAccount类,方法在底部!我一点也不喜欢你所做的:(太多的问题了):/我会给你一个框架,让你跟上。谢谢。我所做的只是一个猜测,因为我不知道如何应用所有这些(我了解编程的基本知识,但我仍在努力改进)
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

public class AccountSpreadsheet {

    private XSSFSheet sheet;
    private final String filename = "Account Information.xlsx";

    public AccountSpreadsheet() {
        try {
            FileInputStream file = new FileInputStream(new File(filename));
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            sheet = workbook.getSheetAt(0);
        } catch (FileNotFoundException e) {
            createSpreadsheet(); //file didn't exist yet
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void createSpreadsheet() {
        XSSFWorkbook workbook = new XSSFWorkbook();
        sheet = workbook.createSheet();
        XSSFRow row = sheet.createRow(0);
        XSSFCell username = row.createCell(0);
        username.setCellValue("Username");
        XSSFCell password = row.createCell(1);
        password.setCellValue("Password");
        save();
    }

    public void addAccount(String username, String password) {
        int newRowIndex = sheet.getPhysicalNumberOfRows();
        XSSFRow newRow = sheet.createRow(newRowIndex);

        XSSFCell usernameCell = newRow.createCell(0);
        usernameCell.setCellValue(username);
        XSSFCell passwordCell = newRow.createCell(1);
        passwordCell.setCellValue(password);
        save();
    }

    private void save() {
        try {
            FileOutputStream outStream = new FileOutputStream(filename);
            sheet.getWorkbook().write(outStream);
            outStream.close();
            sheet = new XSSFWorkbook(new FileInputStream(new File(filename))).getSheetAt(0); //POI bug requires this
        }catch(Exception e){
            e.printStackTrace();
        }
    }

//    public boolean accountExists(String username){
//        //does account exist?
//    }
//
//    public boolean correctLogin(String username, String password) {
//        //correct username and password?
//    }
}