[英]Downloading xls file using java servlet and apache poi library
I am trying to download xls file by fetching data from mysql database table and java servlet and apache poi library.我正在尝试通过从 mysql 数据库表和 java servlet 和 apache poi 库中获取数据来下载 xls 文件。 I am creating fetching data, creating xls file and flushing it into ServletOutputStream.
我正在创建获取数据、创建 xls 文件并将其刷新到 ServletOutputStream 中。
But file is downloading in different format which is not a proper xls file.但是文件正在以不同的格式下载,这不是正确的 xls 文件。 I found code is correct, response header is correct.
我发现代码是正确的,响应 header 是正确的。
SQL query is working fine. SQL 查询工作正常。
Whats wrong?怎么了? Code is here...
代码在这里...
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("GSTR1");
java.sql.ResultSet rs = conx.createStatement().executeQuery(sql);
java.sql.ResultSetMetaData ds = rs.getMetaData();
HSSFRow rowA1 = firstSheet.createRow(0);
int c1 = 1;
while(c1 < ds.getColumnCount())
{
HSSFCell cellA = rowA1.createCell(c1);
Object obj = ds.getColumnLabel(c1);
if(obj != null)
{
String data = obj.toString();
cellA.setCellValue(data);
}
else
{
cellA.setCellValue("");
}
c1++;
}
int r = 1;
while(rs.next())
{
HSSFRow rowA = firstSheet.createRow(r);
int c = 1;
while(c < ds.getColumnCount())
{
HSSFCell cellA = rowA.createCell(c);
Object obj = rs.getString(c);
if(obj != null)
{
String data = obj.toString();
cellA.setCellValue(data);
}
else
{
cellA.setCellValue("");
}
c++;
}
r++;
}
byte[] byteStream = workbook.getBytes();
response.setContentLength(byteStream.length);
servletOutputStream = response.getOutputStream();
servletOutputStream.write(byteStream);
response.addHeader("Content-disposition", "attachment;filename=file.xls");
response.setContentType("application/vnd.ms-excel");
servletOutputStream.flush();
servletOutputStream.close();
I had the same issue.我遇到过同样的问题。 My workaround was to use
org.apache.commons.io.IOUtils.write(content, response.getOutputStream());
我的解决方法是使用
org.apache.commons.io.IOUtils.write(content, response.getOutputStream());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.