-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormToExcelApp.java
More file actions
84 lines (72 loc) · 2.89 KB
/
Copy pathFormToExcelApp.java
File metadata and controls
84 lines (72 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class FormToExcelApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(FormToExcelApp::createAndShowGUI);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Form to Excel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(new GridLayout(4, 2));
JLabel nameLabel = new JLabel("Name:");
JTextField nameField = new JTextField();
JLabel emailLabel = new JLabel("Email:");
JTextField emailField = new JTextField();
JButton submitButton = new JButton("Submit");
frame.add(nameLabel);
frame.add(nameField);
frame.add(emailLabel);
frame.add(emailField);
frame.add(submitButton);
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String email = emailField.getText();
if (!name.isEmpty() && !email.isEmpty()) {
saveToExcel(name, email);
JOptionPane.showMessageDialog(frame, "Data saved to Excel");
} else {
JOptionPane.showMessageDialog(frame, "Please fill all fields", "Warning", JOptionPane.WARNING_MESSAGE);
}
}
});
frame.setVisible(true);
}
private static void saveToExcel(String name, String email) {
String filePath = "FormData.xlsx";
File file = new File(filePath);
Workbook workbook;
Sheet sheet;
try {
if (file.exists()) {
workbook = WorkbookFactory.create(file);
sheet = workbook.getSheetAt(0);
} else {
workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Form Data");
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("Name");
headerRow.createCell(1).setCellValue("Email");
}
int rowCount = sheet.getLastRowNum() + 1;
Row row = sheet.createRow(rowCount);
row.createCell(0).setCellValue(name);
row.createCell(1).setCellValue(email);
try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
workbook.write(fileOut);
}
workbook.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}