简体   繁体   中英

How can I output a user's information entered through a Java Swing GUI onto an excel sheet?

I am writing a program to help keep track of employee seating, however, I am having a difficult time getting the user's information that was captured by a Java Swing GUI to be printed onto an excel sheet. I am using apache POI in order to write to excel as well.

The program iterates through the rows on the excel sheet correctly, but it seems to delete the data that is supposed to be on the first row once the user wants to continue to enter more information. If the user enters information just ONCE (Desk number, employee name, the amount of employees at that desk), presses the JButton "Add To List", it prints the information on the first row like it is supposed to. If the user enters information more than once, it increments the amount of times the "Add To List" button is pressed, but only prints out the last input entered by the user leaving other previous instances of information being written onto the excel rows blank.

Is it a problem with the way the counter is being incremented? Or is it the textfields that need to be adjusted? I apologize for such a long post, but I am teaching myself how to program in java and this problem has been haunting me for a while.

This is my code so far:

import java.awt.EventQueue;
import java.awt.Window;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.util.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import java.io.*;
import javax.swing.DropMode;

public class userMenu {

   private JFrame frmUtilizationSeatingReport; //JFrame being used
   private JTextField txtDeskNum; //Text box that will hold the desk number
   private JTextField txtEmployeeName; //Text box for employee name
   private JTextField txtNumAtDesk; //Text box for the number of employees at that desk
   public int rownum = 1; //My counter being used to increment the row in which input is being stored in

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                userMenu window = new userMenu();
                window.frmUtilizationSeatingReport.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });
}

/**
 * Create the application.
 */

public userMenu() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frmUtilizationSeatingReport = new JFrame();
    frmUtilizationSeatingReport.setTitle("Utilization Seating Report Program");
    frmUtilizationSeatingReport.setBounds(100, 100, 436, 210);
    frmUtilizationSeatingReport.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmUtilizationSeatingReport.getContentPane().setLayout(null);

    JLabel lblDeskNumber = new JLabel("Desk Number:");
    lblDeskNumber.setBounds(20, 11, 163, 21);
    frmUtilizationSeatingReport.getContentPane().add(lblDeskNumber);

    txtDeskNum = new JTextField();
    txtDeskNum.setBounds(42, 30, 121, 20);
    frmUtilizationSeatingReport.getContentPane().add(txtDeskNum);
    txtDeskNum.setColumns(10);

    JLabel lblEmployeeName = new JLabel("Employee Name:");
    lblEmployeeName.setBounds(20, 55, 163, 21);
    frmUtilizationSeatingReport.getContentPane().add(lblEmployeeName);

    txtEmployeeName = new JTextField();
    txtEmployeeName.setBounds(42, 73, 121, 20);
    frmUtilizationSeatingReport.getContentPane().add(txtEmployeeName);
    txtEmployeeName.setColumns(10);

    JLabel lblNumberOfEmployees = new JLabel("Number of Employees at Desk:");
    lblNumberOfEmployees.setBounds(20, 96, 281, 21);
    frmUtilizationSeatingReport.getContentPane().add(lblNumberOfEmployees);

    txtNumAtDesk = new JTextField();
    txtNumAtDesk.setBounds(42, 115, 121, 20);
    frmUtilizationSeatingReport.getContentPane().add(txtNumAtDesk);
    txtNumAtDesk.setColumns(10);

    JButton btnAdd = new JButton("Add To List");
    btnAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent b) {

            String deskNumber = ""; //Will take the desk number in as a string
            int empsAtDesk = 0; //The number of employees at the desk as an int
            String employeeName = ""; //Employee Name
            boolean keepRunning = true; 

            deskNumber = txtDeskNum.getText();
            empsAtDesk = Integer.parseInt(txtNumAtDesk.getText());
            employeeName = txtEmployeeName.getText();       

    //Blank workbook
            HSSFWorkbook workbook = new HSSFWorkbook();

       //Blank sheet
            HSSFSheet sheet = workbook.createSheet("Seating Details");

    //create heading
            Row rowHeading = sheet.createRow(0);
            rowHeading.createCell(0).setCellValue("Desk:");
            rowHeading.createCell(1).setCellValue("Employee(s)Name:");
            rowHeading.createCell(2).setCellValue("Number At Desk:");

    //Create 'total' headings
            Row rowtotal = sheet.createRow(71);
            rowtotal.createCell(0).setCellValue("Total:");
            CellStyle stylerowtotal = workbook.createCellStyle();
            Font totalfonts = workbook.createFont();
            totalfonts.setBold(true);
            totalfonts.setFontName(HSSFFont.FONT_ARIAL);
            totalfonts.setFontHeightInPoints((short) 11);
            stylerowtotal.setFont(totalfonts);
            stylerowtotal.setVerticalAlignment(CellStyle.ALIGN_CENTER);
            rowtotal.getCell(0).setCellStyle(stylerowtotal);

            Row rowpercent = sheet.createRow(72);
            rowpercent.createCell(0).setCellValue("Total %/Day:");
            stylerowtotal = workbook.createCellStyle();
            totalfonts = workbook.createFont();
            totalfonts.setBold(true);
            totalfonts.setFontName(HSSFFont.FONT_ARIAL);
            totalfonts.setFontHeightInPoints((short) 11);
            stylerowtotal.setFont(totalfonts);
            stylerowtotal.setVerticalAlignment(CellStyle.ALIGN_CENTER);
            rowpercent.getCell(0).setCellStyle(stylerowtotal);

            Row percentMTh = sheet.createRow(73);
            percentMTh.createCell(0).setCellValue("Total %/Week M-Th:");
            stylerowtotal = workbook.createCellStyle();
            totalfonts = workbook.createFont();
            totalfonts.setBold(true);
            totalfonts.setFontName(HSSFFont.FONT_ARIAL);
            totalfonts.setFontHeightInPoints((short) 11);
            stylerowtotal.setFont(totalfonts);
            stylerowtotal.setVerticalAlignment(CellStyle.ALIGN_CENTER);
            percentMTh.getCell(0).setCellStyle(stylerowtotal);

            Row percentMFri = sheet.createRow(74);
            percentMFri.createCell(0).setCellValue("Total %/Week M-F:");
            stylerowtotal = workbook.createCellStyle();
            totalfonts = workbook.createFont();
            totalfonts.setBold(true);
            totalfonts.setFontName(HSSFFont.FONT_ARIAL);
            totalfonts.setFontHeightInPoints((short) 11);
            stylerowtotal.setFont(totalfonts);
            stylerowtotal.setVerticalAlignment(CellStyle.ALIGN_CENTER);
            percentMFri.getCell(0).setCellStyle(stylerowtotal);

            Row seatsAvai = sheet.createRow(75);
            seatsAvai.createCell(0).setCellValue("Total Seats Available:");
            stylerowtotal = workbook.createCellStyle();
            totalfonts = workbook.createFont();
            totalfonts.setBold(true);
            totalfonts.setFontName(HSSFFont.FONT_ARIAL);
            totalfonts.setFontHeightInPoints((short) 11);
            stylerowtotal.setFont(totalfonts);
            stylerowtotal.setVerticalAlignment(CellStyle.ALIGN_CENTER);
            seatsAvai.getCell(0).setCellStyle(stylerowtotal);

    //Create Cell Formulas

          //Total number of employees at a desk cell formula       
            rowtotal.createCell(2).setCellFormula("SUM(C2:C71)");

          //Total percentage for the day
            rowpercent.createCell(2).setCellFormula("(SUM(C2:C71) / 78) * 100");

    //Font size and style loop for my headers

                for(int i = 0; i < 3; i++)
                {
                    CellStyle stylerowHeading = workbook.createCellStyle();
                    Font font = workbook.createFont();
                    font.setBold(true);
                    font.setFontName(HSSFFont.FONT_ARIAL);
                    font.setFontHeightInPoints((short) 11);
                    stylerowHeading.setFont(font);
                    stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);
                    rowHeading.getCell(i).setCellStyle(stylerowHeading);
                }


    //This data needs to be written (Object[])
                Map <String, Object[]> data = new TreeMap<String, Object[]>();
                data.put("5", new Object[] {deskNumber, employeeName, empsAtDesk});

                if(keepRunning){ 
    //Iterate over data and write to sheet
                Set<String> keyset = data.keySet();
                for(String Key : keyset)
                {
                    Row row = sheet.createRow(rownum++);
                    Object [] objArr = data.get(Key);
                    int cellnum = 0;
                    for(Object obj : objArr)
                    {
                        Cell cell = row.createCell(cellnum++);
                        if(obj instanceof String)
                        {
                            cell.setCellValue((String)obj);
                        }
                        else if(obj instanceof Integer)
                        {
                            cell.setCellValue((Integer)obj);
                        }

                    } 


    //Auto size my columns that will be filled out with user input info.            
                for (int i = 0; i < 3; i++)
                {
                    sheet.autoSizeColumn(i);
                }

               } //top for loop brace

        try{

    //save to excel file
                FileOutputStream out = new FileOutputStream(new File("Employee Seating Report.xls"));
                workbook.write(out);
                out.flush();
                out.close();
                workbook.close();
                System.out.println("Excel Written Succesfully..." + '\n');

            } catch (FileNotFoundException e1) {

                e1.printStackTrace();

            } catch (IOException e1){

                e1.printStackTrace();

            } catch (Exception e1) {

                System.out.println(e1.getMessage());
            }

        //Empty text fields once user presses "Add To List" button
        txtDeskNum.setText("");
        txtEmployeeName.setText("");
        txtNumAtDesk.setText("");

                }//If statement end brace

        }//Public void end brace

    });

    btnAdd.setBounds(214, 42, 129, 23);
    frmUtilizationSeatingReport.getContentPane().add(btnAdd);

    JButton btnExit = new JButton("End Program");
    btnExit.addActionListener(new ActionListener() {
    //If the user presses the"End Program" button, close the program.   
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    btnExit.setBounds(214, 95, 129, 23);
    frmUtilizationSeatingReport.getContentPane().add(btnExit);
}

}

You are creating your workbook inside your addActionListener and writing a new Excel file in it, so it will always overwrite the previous written data.

Try collecting all the data to a List of objects EmployeeDesk on click of your button btnAdd and create a new button that creates the workbook and writes the data from your list to your Excel, so you'll have a new button btnSave that creates the Excel file and writes everthing.

I'm not an expert of the .xls format and haven't used it but i've written to csv files and you can use the java standard library to do so fairly simply. Maybe a jtable would remove some of the ambiguity you have with creating rows columns and headers. It would certainly be less verbose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM