将用户输入到excel(Apache poi)

时间:2014-11-16 23:55:50

标签: 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.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()方法的类。

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;


public class ViewAccount extends JFrame implements ActionListener {

    AccountSpreadsheet spreadsheet = new AccountSpreadsheet();
    JLabel userName = new JLabel("Username:");
    JTextField enterUserName = new JTextField(null,15);
    JLabel Password = new JLabel("Password:");
    JTextField enterPassword = new JTextField(null,15);
    JButton log = new JButton("Login");
    Account account;    

    public ViewAccount() {

        add(userName);
        add(enterUserName);
        add(Password);
        add(enterPassword);
        add(log);
        log.setPreferredSize(new Dimension(250, 40));
        log.addActionListener(this);

        setTitle("Login");
        setVisible(true);
        setSize(300,150);
        setLayout(new FlowLayout());
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == log) {
            confirmUsername();
            }
        }
    public void confirmUsername() {
        AccountSpreadsheet Spreadsheet = new AccountSpreadsheet();
        CreateAccount Acct = new CreateAccount();
        String passString = Acct.passString;
        String userName = Acct.userName;


        for (Iterator<Row> rit = Spreadsheet.sheet.rowIterator(); rit.hasNext();) {
            Row row = rit.next();
            for (Iterator<Cell> cit = row.cellIterator(); cit.hasNext();) {
                Cell cell = cit.next();
                String name = cell.getStringCellValue();
                if(userName == name) {
                    cit.next();
                    if(passString == name){
                        System.out.println("Log success");
                    }else{
                        System.out.println("ERROR");
                    }
                }else{
                    System.out.println("ERROR");
                }

            }
        }
    }
}

我知道调用CreateAccount会从CreateAccount构造函数中弹出另一个窗口,但我不确定如何将userName和passString放入方法中。

1 个答案:

答案 0 :(得分:1)

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

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(用户名,密码)。