0

所以,我正在开发一个基于 GUI 的应用程序,它使用 Apache POI 从 Excel 读取数据并使用JAVA AWT/SWING基于窗口应用程序显示它。因此,首先我将 Apache 集成POIGUI基于JAVA项目的项目中。

所以,现在我正在尝试从 excel 访问特定的单元格数据并在 GUI 应用程序中打印它。我已经整理了如何从excel到Java中获取特定的单元格数据以及如何使用Jlabel. 要继续它,我需要将单元格数据发送到JLabel.

我已经完成以下操作来获取单元格数据:显然,我们有cell来自Cell类的对象。我如何将此cell数据发送到JLabel

我有以下代码JLabel

try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx")) {  
            Workbook wb = WorkbookFactory.create(inp);  
            Sheet sheet = wb.getSheetAt(0);  
            Row row = sheet.getRow(2);  
            Cell cell = row.getCell(2);
            if (cell != null)  
                System.out.println("Data: "+cell);  
            else  
                System.out.println("Cell is empty");  
    }catch(Exception e) {  
        System.out.println(e);  
    } 

显然我们有cell来自Cell类的对象。我如何将此cell数据发送到JLable

我有以下代码JLable

这里我们按下按钮后内容的Lable变化。


lblNewLabel = new JLabel("Hey there. Your GPA is");
        lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
        lblNewLabel.setBounds(100, 46, 298, 55);
        frame.getContentPane().add(lblNewLabel);


JButton btnNewButton = new JButton("Show me!");
        btnNewButton.setForeground(Color.BLUE);
        btnNewButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 16));
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null, "Hello World!");
                lblNewLabel.setText(cell);
            }
        });

lblNewLabel.setText(cell);

但它显示错误。我什至声明了一个新字符串并使用cell对象传递它。但它也没有奏效。

我正在寻找一种将输出从 Cell 传递到JLabel.

两者都仅在主要功能中。

下面是整个代码。

package com;

import java.io.FileInputStream;  
import java.io.InputStream;  
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;  
import org.apache.poi.ss.usermodel.WorkbookFactory;  
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JLabel;

public class GUI {

    private JFrame frame;
    private JLabel lblNewLabel;
    private JTextField textField;
    private JTextField textField_1;
    private JLabel lblNewLabel_1;
    private JTextField textField_2;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx")) {  
            Workbook wb = WorkbookFactory.create(inp);  
            Sheet sheet = wb.getSheetAt(0);  
            Row row = sheet.getRow(2);  
            Cell cell = row.getCell(2);
            if (cell != null)  
                System.out.println("Data: "+cell);  
            else  
                System.out.println("Cell is empty");  
    }catch(Exception e) {  
        System.out.println(e);  
    }  


        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUI window = new GUI();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public GUI() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 605, 418);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnNewButton = new JButton("Show me!");
        btnNewButton.setForeground(Color.BLUE);
        btnNewButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 16));
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null, "Hello World!");
                lblNewLabel.setText(cell);
            }
        });
        btnNewButton.setBounds(147, 133, 130, 31);
        frame.getContentPane().add(btnNewButton);

        lblNewLabel = new JLabel("Hey there. Your GPA is");
        lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
        lblNewLabel.setBounds(100, 46, 298, 55);
        frame.getContentPane().add(lblNewLabel);

        textField = new JTextField();
        textField.setBounds(63, 214, 96, 19);
        frame.getContentPane().add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(342, 214, 96, 19);
        frame.getContentPane().add(textField_1);
        textField_1.setColumns(10);

        lblNewLabel_1 = new JLabel("Answer-");
        lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 24));
        lblNewLabel_1.setBounds(139, 323, 122, 48);
        frame.getContentPane().add(lblNewLabel_1);

        textField_2 = new JTextField();
        textField_2.setBounds(301, 329, 174, 42);
        frame.getContentPane().add(textField_2);
        textField_2.setColumns(10);

        JButton btnNewButton_1 = new JButton("Multiply");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int a,b,ans;
                try {
                    a=Integer.parseInt(textField.getText());
                    b=Integer.parseInt(textField_1.getText());
                    ans=a*b;
                    textField_2.setText(Integer.toString(ans));

                }catch(Exception e1) {
                    JOptionPane.showMessageDialog(null,"Enter valid number");
                }
            }
        });
        btnNewButton_1.setBounds(90, 264, 85, 21);
        frame.getContentPane().add(btnNewButton_1);

        JButton btnNewButton_2 = new JButton("Divide");
        btnNewButton_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int a,b,ans;
                try {
                    a=Integer.parseInt(textField.getText());
                    b=Integer.parseInt(textField_1.getText());
                    ans=a/b;
                    textField_2.setText(Integer.toString(ans));

                }catch(Exception e2) {
                    JOptionPane.showMessageDialog(null,"Enter valid number");
                }
            }
        });

        btnNewButton_2.setBounds(330, 264, 85, 21);
        frame.getContentPane().add(btnNewButton_2);
    }
}

不要介意所有其他 GUI 代码。它们只是一些按钮、文本字段。

4

2 回答 2

1

首先,您需要Cell cell在方法的范围内获得,initialize否则它Cell cell也必须是类成员JLabel lblNewLabel

另一种解决方案是使用公共方法从工作簿中获取单元格内容,然后可以从该方法中调用该initialize方法。

那么a的setText方法JLabel需要aString作为参数。因此,您需要将 to 的内容转换cellString.

所以最简单的解决方案是

...
String cellContent = cell.toString();
...

但这不是首选的方法。而是使用DataFormatterof从asapache poi中获取单元格内容。将得到与显示单元格内容相同的内容。CellStringDataFormatterStringExcel

...
DataFormatter formatter = new DataFormatter();
...
String cellContent = formatter.formatCellValue(cell);
...

如果可以有公式单元格并且您需要公式结果而不是公式,那么您将需要FormulaEvaluator额外的。

...
DataFormatter formatter = new DataFormatter();
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
...
String cellContent = formatter.formatCellValue(cell, evaluator);
...

因此,要扩展您的代码,您可以使用以下方法:

...
public String getCellContent() {
 String cellContent = "";
 try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx"); 
      Workbook wb = WorkbookFactory.create(inp)) {  
  DataFormatter formatter = new DataFormatter();
  FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  Sheet sheet = wb.getSheetAt(0);  
  Row row = sheet.getRow(2);
  Cell cell = null;
  if (row != null) cell = row.getCell(2);
  cellContent = formatter.formatCellValue(cell, evaluator);
 } catch (Exception e) {
  e.printStackTrace();
 }
 return cellContent;
}
...

然后在你的initialize方法中:

...
            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null, "Hello World!");
                lblNewLabel.setText(getCellContent());
            }
...

但当然,这将始终从工作表中获得相同的单元格内容。因此,对于实际使用,getCellContent必须具有参数来告诉应读取哪个具体单元。然后该方法不应每次获取单元格内容时都打开工作簿。所以Workbook wbDataFormatter formatter并且FormulaEvaluator evaluator应该是类成员并且只创建一次initialize

于 2020-04-04T14:07:36.413 回答
0

您正在尝试访问cell,但它是在另一个范围内定义的。您可以创建返回单元格字符串的方法。

public String getCell() {
        try (InputStream inp = new FileInputStream("C:\\Users\\mohin\\OneDrive\\Desktop\\a.xlsx")) {  
        Workbook wb = WorkbookFactory.create(inp);  
        Sheet sheet = wb.getSheetAt(0);  
        Row row = sheet.getRow(2);  
        Cell cell = row.getCell(2);
        if (cell != null)  
            return cell.toString(); 
}catch(Exception e) {  
    System.out.println(e);  
}  

返回空值;} 然后像这样访问它:

JButton btnNewButton = new JButton("Show me!");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //JOptionPane.showMessageDialog(null, "Hello World!");
            lblNewLabel.setText(getCell());
        }
    });
于 2020-04-04T13:58:03.820 回答