我在数据库中有一些数据,通过一些 JSP 和 servlet,我制作了一个具有界面的 Web 应用程序。通过界面,我可以选择数据库中表的列名,并在下一个文本框中键入关键字,然后可以搜索那些行包含该特定列中的关键字。我使用引导表来查看表格格式的输出。 我希望,如果用户单击表格底部的“保存”按钮,则会打开一个弹出窗口,他可以输入名称并选择位置,然后保存文件。
所有其他事情,例如获取数据和显示,都没有问题。
最佳答案
您可以使用 HSSFRow 将您的 jsp 列表解析为 java 中的 Excel 工作表
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
然后你需要为 Excel 工作表创建一个标题
//对于标题
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("NAME");
现在您将根据列表大小在列中填充数据。
//列表的其余部分
int rownum = 1;
for (YourObject obj : listOfObjects) {
Row row = sheet.createRow(rownum++);
row.createCell(0).setCellValue(obj.getID());
row.createCell(1).setCellValue(obj.getName());
}
将数据写入xls文件
try {
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook.write(outByteStream);
byte[] outArray = outByteStream.toByteArray();
response.setContentType("application/vnd.ms-excel");
response.setContentLength(outArray.length);
response.setHeader("Expires:", "0"); // eliminates browser caching
response.setHeader("Pragma","cache");
response.setHeader("Cache-Control","private");
response.setHeader("Content-Disposition", "attachment; filename=sample.xls");
OutputStream outStream = response.getOutputStream();
outStream.write(outArray);
outStream.flush();
outStream.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e)
{
e.printStackTrace();
}
希望对你有帮助!!!
关于mysql - 如何在jsp中将生成的表响应保存到excel文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30914525/