Before doing Excel export, I will first write the file on the server, and then download it, and later found that the original can directly write the file in the output stream inside.
Here is a small demo:
Package Com.huaqin.fcstrp.util;import Java.io.ioexception;import Java.io.outputstream;import Java.io.unsupportedencodingexception;import Java.net.urlencoder;import Javax.servlet.http.HttpServletResponse; Import Org.apache.poi.hssf.usermodel.hssfworkbook;import Org.apache.poi.ss.usermodel.cell;import Org.apache.poi.ss.usermodel.row;import Org.apache.poi.ss.usermodel.sheet;public class Write {private HSSFWorkbook Workbook = null;/** * * @param response download request response */public void Createexcel (HttpServletResponse response) {//Create WOR Kbook workbook = new Hssfworkbook (); add worksheet (The XLS file generated when you do not add Sheet will be opened with an error) Sheet Sheet1 = Workbook.createsheet ("Sheet1"); OutputStream out = null; try {out = Response.getoutputstream (); String filename = "Test.xls";//FileName Response.setcontenttype ("application/x-msdownload"); Response.setheader ("Content-disposition", "attachment; Filename= "+ urlencoder.encode (fileName," UTF-8 ")); Row row = Workbook.getsheet ("Sheet1"). CreateRow (0); Create the first line for (int i = 0;i < 10;i++) {cell cell = Row.createcell (i); Cell.setcellvalue ("test Data" +i); }workbook.write (out);} catch (Exception e) {e.printstacktrace ();} finally {try {out.close (); } catch (IOException e) {e.printstacktrace (); } } }}
Call:
/** * Download 2 * @param request * @param response * @return * @throws filenotfoundexception * /@RequestMapping (value = "/dow Nload2 ") @ResponseBodypublic void Download2 (httpservletrequest request,httpservletresponse response) throws FileNotFoundException { Write write = new write (); Write.createexcel (response);}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
How to write Excel directly in the output stream when you do Excel export