Apache POI生成Excel


public InputStream getInputStream()
{
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet1");

HSSFRow row = sheet.createRow(0);

HSSFCell cell = row.createCell((short) 0);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("序号");

cell = row.createCell((short) 1);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("姓");

cell = row.createCell((short) 2);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("名");

cell = row.createCell((short) 3);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("年龄");

List<User> list = this.findAll();

for (int i = 0; i < list.size(); ++i)
{
User user = list.get(i);

row = sheet.createRow(i + 1);

cell = row.createCell((short) 0);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(i + 1);

cell = row.createCell((short) 1);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getFirstname());

cell = row.createCell((short) 2);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getLastname());

cell = row.createCell((short) 3);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getAge());
}

File file = new File("test.xls");

try
{
OutputStream os = new FileOutputStream(file);
wb.write(os);
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}

InputStream is = null;
try
{
is = new FileInputStream(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}

return is;

}


上面在服务器端生成test.xls时这样会造成多用户不同步的情况。

解决办法:
1.让每个用户产生一个随机名字的文件
bug:多个用户的话,这样的垃圾文件会越来越多。
所以,当用户下载完后,过一段时间就将他删掉。
生成一个文件后通过线程将文件删除。

new Thread(new Runnable()
{
public void run()
{
try
{
Thread.sleep(15000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}

file.delete();//删除临时文件
}
}).start();

或者服务器启动就删除
web.xml

<servlet>
<servlet-name>DeleteFilesServlet</servlet-name>
<servlet-class>com.test.servlet.DeleteFilesServlet</servlet-class>
<!-- 这个是用来server自动访问,不需要urlmapping -->
<load-on-startup>8</load-on-startup>
</servlet>



public class DeleteFilesServlet extends HttpServlet
{

public void destroy()
{

}

public void init() throws ServletException
{
// File file = new File(".");
//
// File[] subFiles = file.listFiles();
//
// for(File f : subFiles)
// {
// if(f.getName().endsWith("xls"))
// {
// f.delete();
// }
// }

File file = new File(".");

File[] subFiles = file.listFiles(new FileFilter()
{
public boolean accept(File pathname)
{
if(pathname.getName().endsWith("xls"))
{
return true;
}

return false;
}
}
);

for(File f : subFiles)
{
f.delete();
}
}

}


2.将构造好的流放到内存里,不会在服务

器端产生大量的临时文件。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值