java读取Access第一行并导出表格
时间: 2024-05-07 17:19:08 浏览: 52
以下是Java代码示例,使用JDBC连接Access数据库并读取第一行数据并导出为表格:
```java
import java.io.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class AccessTableExporter {
public static void main(String[] args) {
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=/path/to/your/access/database.mdb";
String query = "SELECT * FROM YourTable";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
Object[] columnNames = new Object[columnCount];
for (int i = 0; i < columnCount; i++) {
columnNames[i] = metaData.getColumnLabel(i + 1);
}
DefaultTableModel model = new DefaultTableModel(new Object[0][0], columnNames);
if (rs.next()) {
Object[] rowData = new Object[columnCount];
for (int i = 0; i < columnCount; i++) {
rowData[i] = rs.getObject(i + 1);
}
model.addRow(rowData);
}
JTable table = new JTable(model);
JFileChooser fileChooser = new JFileChooser();
int userSelection = fileChooser.showSaveDialog(null);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(fileToSave));
for (int i = 0; i < columnCount; i++) {
writer.write(columnNames[i] + "\t");
}
writer.newLine();
for (int i = 0; i < columnCount; i++) {
writer.write(model.getValueAt(0, i) + "\t");
}
writer.newLine();
writer.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
请将代码中的 `url` 和 `query` 变量替换为您自己的Access数据库的URL和查询语句,以及您自己的表名称。运行此代码将显示一个文件选择器,允许您选择要将表格导出到的文件。文件将以制表符分隔的文本文件格式进行导出。
阅读全文