下面的程序将单个表的数据导出到 excel 文件中。我的问题是,如果我有两个表,那么如何将其数据导出到同一个 excel 文件的两个不同工作表中?
假设工作表 1 中的 tab1 数据和同一个 Excel 工作表的工作表 2 中的 tab2 数据
public class CreateExcelFile{
public static void main(String[]args){
try{
String filename="c:/data.xls" ;
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("SNo");
rowhead.createCell((short) 1).setCellValue("Name");
rowhead.createCell((short) 2).setCellValue("Address");
rowhead.createCell((short) 3).setCellValue("Contact No");
rowhead.createCell((short) 4).setCellValue("E-mail");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:456/test", "root", "root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from employee");
int i=1;
while(rs.next()){
HSSFRow row= sheet.createRow((short)i);
row.createCell((short) 0).setCellValue(Integer.toString(rs.getInt("id")));
row.createCell((short) 1).setCellValue(rs.getString("name"));
row.createCell((short) 2).setCellValue(rs.getString("address"));
row.createCell((short) 3).setCellValue(Integer.toString(rs.getInt("contactNo")));
row.createCell((short) 4).setCellValue(rs.getString("email"));
i++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
} catch ( Exception ex ) {
System.out.println(ex);
}
}
}