swing表格数据导出

木子空间Pro 2023-08-18 20:02:51

效果

img

主要代码

public class MeetingTableApp extends JFrame {
    // 省略其他代码...

    public MeetingTableApp() {
        // 省略其他代码...

        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("添加");
        // 省略其他代码...

        JButton exportButton = new JButton("导出");
        exportButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                exportTableData();
            }
        });
        buttonPanel.add(exportButton);

        add(formPanel, BorderLayout.EAST);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void exportTableData() {
        JFileChooser fileChooser = new JFileChooser();
        int choice = fileChooser.showSaveDialog(this);
        if (choice == JFileChooser.APPROVE_OPTION) {
            try {
                String filePath = fileChooser.getSelectedFile().getPath();
                BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));

                // 写入表头
                for (int i = 0; i < table.getColumnCount(); i++) {
                    writer.write(table.getColumnName(i));
                    writer.write("\t");
                }
                writer.newLine();

                // 写入表格数据
                for (int row = 0; row < table.getRowCount(); row++) {
                    for (int col = 0; col < table.getColumnCount(); col++) {
                        Object value = table.getValueAt(row, col);
                        writer.write(value.toString());
                        writer.write("\t");
                    }
                    writer.newLine();
                }

                writer.close();
                JOptionPane.showMessageDialog(this, "导出成功!");
            } catch (IOException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "导出失败!");
            }
        }
    }

    // 省略其他代码...
}


...全文
169 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

14

社区成员

发帖
与我相关
我的任务
社区描述
学习交流,在线答疑,远程协助,程序定制与DIY,直接私聊群主即可,忙碌时段回复有延迟!
后端经验分享程序人生 个人社区 广东省·广州市
社区管理员
  • 木子空间Pro
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧