简体   繁体   English

我如何使用Apache POI在Excel中增加行

[英]How can i increment the rows in excel using apache poi

I am writing a program to keep track of employee seating using java and apache poi to write to a excel sheet. 我正在编写一个程序,以使用java和apache poi来记录Excel表格来跟踪员工的座位。 The program will prompt the user to enter the desk number, employee name(s), and the number of employees sitting at that desk. 该程序将提示用户输入办公桌编号,员工姓名和坐在该办公桌上的员工人数。 My problem is that the program only writes the last information that was entered by the user, erasing what was previously entered in that row. 我的问题是,该程序仅写入用户输入的最后信息,从而删除了先前在该行中输入的信息。 How can I keep what was entered in the first row of the excel sheet? 如何保留Excel工作表第一行中输入的内容? I have it set on a loop where the user will keep being prompted for the seating information until the user enters EXIT. 我将其设置在一个循环中,在该循环中,将一直提示用户输入座位信息,直到用户输入EXIT。 I want it to increment down a row every time new information is entered. 我希望每次输入新信息时它都会向下递增。

This is what I have so far: 这是我到目前为止的内容:

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.*;

public class EmployeeSeatingRep {

public static void main(String[] args){

    String deskNumber = "";
    String employeeName = "";
    int empsAtDesk = 0;
    boolean keepRunning = true;


//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:");

//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);
        }
    while(keepRunning){
        Scanner scnr = new Scanner(System.in);

        System.out.print("Enter desk number: ");
        deskNumber = scnr.nextLine();
        if(deskNumber.equals("EXIT"))
        {
            System.out.print("You have ended the program");
            System.exit(0);
        }
        else
        {
            System.out.print("Enter employee name: ");
            employeeName = scnr.nextLine();
            System.out.print("Enter amount of employees at desk: ");
            empsAtDesk = scnr.nextInt();







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

//Iterate over data and write to sheet
        Set<String> keyset = data.keySet();
        int rownum = 1;
        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);
                }
            }
            if(!(deskNumber.equals("EXIT")))
            {
                rownum++;

        }

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

 //save to excel file
        FileOutputStream out = new FileOutputStream(new File("Employee Seating Report.xls"));
        workbook.write(out);
        out.flush();
        out.close();
        System.out.println("Excel Written Succesfully...");
    } catch (FileNotFoundException e) {

        e.printStackTrace();

    } catch (IOException e){

        e.printStackTrace();

    } catch (Exception e) {

        System.out.println(e.getMessage());
    }
  } 
}       
}//pub static void end brace    
}//pub class end brace

The issue you're describing is caused by this: 您正在描述的问题是由以下原因引起的:

int rownum = 1; <--
for(String Key : keyset)
{
    Row row = sheet.createRow(rownum++);

You've declared rownum inside your main loop and as a result, it will always be 1. 您已经在主循环中声明了rownum ,因此,它将始终为1。

Rather than creating, populating and writing out your data map every time through the loop, it would simplify things greatly if you use the loop to build a List of row objects, then write them to the file when the user is done. 如果不使用循环来构建,填充和写入data映射,而是使用循环来构建行对象List ,然后在用户完成操作后将其写入文件,则可以大大简化操作。

Every information entered by the user should be added to a new row in excel so you need to create row outside your for loop and only create cells in for loop for entered data. 用户输入的每个信息都应添加到excel中的新行中,因此您需要在for循环外创建一行,并且仅在for循环中为输入的数据创建单元格。 Something like this: 像这样:

    Scanner scnr = new Scanner(System.in);

    System.out.print("Enter desk number: ");
    deskNumber = scnr.nextLine();
    if(deskNumber.equals("EXIT"))
    {
        System.out.print("You have ended the program");
        System.exit(0);
    }
    else
    {
        System.out.print("Enter employee name: ");
        employeeName = scnr.nextLine();
        System.out.print("Enter amount of employees at desk: ");
        empsAtDesk = scnr.nextInt(); scnr.next();
        Row row = sheet.createRow(rownum++);
        Object [] objArr = new Object[] {deskNumber, employeeName, empsAtDesk};
        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);
            }
        }
  }

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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