1.在pom.xml添加maven路径
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
2.jsp页面中
js方法
function exportdata()
{
//拼接发送链接
$( "#exportIframe" ).attr( "src","<%=basePath%>" +"messagetemplate/get");
}
html代码
<iframe id="exportIframe" style="border:0px;width:0px;height:0px;" src=""></iframe>
java代码
@RequestMapping( "/get" )
public void do_get(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
List<MessageTemplate> records = messageTemplateModel.queryAllRecord();
String[] titles = {"ID", "Code", "Content", "Name", "OutCode"};
Workbook wb;
wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("Business Plan");
Row headerRow = sheet.createRow(0);
for (int i = 0; i < titles.length; i++)
{
Cell cell = headerRow.createCell(i);
cell.setCellValue(titles[i]);
}
sheet.createFreezePane(0, 1);
Row row;
Cell cell;
int rownum = 1;
String[][] data ;
data = new String[records.size()][5];
for( int a = 0; a < records.size(); a++ )
{
MessageTemplate messageTemplateDomain = records.get(a);
data[a][0] = String.valueOf( messageTemplateDomain.getId() ) ;
data[a][1] = messageTemplateDomain.getCode() ;
data[a][2] = messageTemplateDomain.getContent() ;
data[a][3] = messageTemplateDomain.getName() ;
data[a][4] = messageTemplateDomain.getOutCode() ;
}
for (int i = 0; i < data.length; i++, rownum++)
{
row = sheet.createRow(rownum);
if(data[i] == null) continue;
for (int j = 0; j < data[i].length; j++)
{
cell = row.createCell(j);
cell.setCellValue(data[i][j]);
}
}
String docsPath = request.getSession().getServletContext().getRealPath("docs");
String fileName = "export2007中文_" + System.currentTimeMillis() + ".xls";
String filePath = "C:\\Users\\admin\\Desktop\\"+ fileName;
FileOutputStream out = new FileOutputStream( filePath );
wb.write(out);
out.close();
download(filePath, response);
wb.close();
}
private void download(String path, HttpServletResponse response)
{
try
{
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.getBytes(),"ISO-8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
toClient.write(buffer);
toClient.flush();
toClient.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}