【发布时间】:2018-08-23 09:46:21
【问题描述】:
我必须从数据库中的各个表中检索数据并将每个表值存储为 ResultSet。然后我需要在单个 excel 文件的每张表中填充每个 ResultSet 值。因此,我需要将每个表值与列名写入单独的 Excel 文件表中。提前致谢
【问题讨论】:
-
您实际上并没有提出问题或描述确切的问题 - 您所做的只是告诉我们您的任务是什么。
标签: java jdbc apache-poi
我必须从数据库中的各个表中检索数据并将每个表值存储为 ResultSet。然后我需要在单个 excel 文件的每张表中填充每个 ResultSet 值。因此,我需要将每个表值与列名写入单独的 Excel 文件表中。提前致谢
【问题讨论】:
标签: java jdbc apache-poi
我从其他人那里得到了这个,但我认为它也可以应用于你的情况。
try {
Class.forName("driverName"); //driver name
Connection con = DriverManager.getConnection("url", "user", "pass");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select * from tablename"); //table you want to get information from
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheetName"); //name the sheet
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("CellHeadName1"); //name the cells
rowhead.createCell((short) 1).setCellValue("CellHeadName2");
rowhead.createCell((short) 2).setCellValue("CellHeadName3");
int i = 1;
while (rs.next()){
HSSFRow row = sheet.createRow((short) i);
row.createCell((short) 0).setCellValue(Integer.toString(rs.getInt("column1"))); //name columns
row.createCell((short) 1).setCellValue(rs.getString("column2"));
row.createCell((short) 2).setCellValue(rs.getString("column3"));
i++;
}
String xlss= "g:/test.xls"; //the file you want the data put into
FileOutputStream fileOut = new FileOutputStream(xlss);
workbook.write(fileOut);
fileOut.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
【讨论】: