lygyh9985825 发表于 2017-1-3 11:24:13

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.将构造好的流放到内存里,不会在服务
器端产生大量的临时文件。
页: [1]
查看完整版本: Apache POI生成Excel