使用apache的poi来实现数据导出到excel的功能——方式一
利用poi导出复杂样式的excel表格的实现。
我们要实现的效果是:

我们利用提前设计好模板样式,再在模板中填充数据的方式。
首先,pom.xml引入poi。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
然后,编写代码部分。
@RequestMapping("/print")
public void print(String param,HttpServletResponse response, HttpServletRequest request) throws Exception{
//获取模板存放的路径
String path=request.getSession().getServletContext().getRealPath("/")+"/ExcelTemplate/";
InputStream is=new FileInputStream(new File(path+"表单模板.xls"));
HSSFWorkbook wb=new HSSFWorkbook(is);
HSSFSheet sheet = wb.getSheetAt();
Row nRow=null;
Cell nCell=null;
//行号
int rowNo=;
//列号
int colNo=;
//获取模板上的第六行单元格样式
nRow=sheet.getRow();
//内容样式
nCell=nRow.getCell();
CellStyle textStartStyle=nCell.getCellStyle();
nCell=nRow.getCell();
CellStyle textCenterStyle=nCell.getCellStyle();
nCell=nRow.getCell();
CellStyle textEndStyle=nCell.getCellStyle();
//大标题================================================
nRow=sheet.getRow(rowNo++); //获取第一行对象
nCell=nRow.getCell(colNo); //获取第一个单元格对象
nCell.setCellValue("入流入库单");
//获取第二行
colNo=;
nRow=sheet.getRow(rowNo++);
nCell=nRow.getCell(colNo++);//第二行第二列
nCell.setCellValue("测试客户");
nCell=nRow.getCell(colNo+=);//第二行第四列
nCell.setCellValue("2018-09-18");
//获取第三行
colNo=;
nRow=sheet.getRow(rowNo++);
nCell=nRow.getCell(colNo++);//第三行第二列
nCell.setCellValue("豫A 123");
nCell=nRow.getCell(colNo+=);//第三行第四列
nCell.setCellValue("-18");
//获取第四行
colNo=;
nRow=sheet.getRow(rowNo++);
nCell=nRow.getCell(colNo++);//第四行第二列
nCell.setCellValue("郑州");
nCell=nRow.getCell(colNo+=);//第四行第四列
nCell.setCellValue("漯河");
//插入行
for(int j=;j<;j++){
colNo=;
rowNo++;
sheet.shiftRows(rowNo, sheet.getLastRowNum(), ,true,false);
nRow=sheet.createRow(rowNo);
nCell=nRow.createCell(colNo++);
nCell.setCellValue("");
nCell.setCellStyle(textCenterStyle);
nCell=nRow.createCell(colNo++);
nCell.setCellValue("小苹果");
nCell.setCellStyle(textCenterStyle);
nCell=nRow.createCell(colNo++);
nCell.setCellValue("1kg/袋");
nCell.setCellStyle(textCenterStyle);
nCell=nRow.createCell(colNo++);
nCell.setCellValue("");
nCell.setCellStyle(textCenterStyle);
nCell=nRow.createCell(colNo++);
nCell.setCellValue("");
nCell.setCellStyle(textCenterStyle);
nCell=nRow.createCell(colNo++);
nCell.setCellValue("仓库1");
nCell.setCellStyle(textCenterStyle);
nCell=nRow.createCell(colNo++);
nCell.setCellValue("beizhu");
nCell.setCellStyle(textEndStyle);
}
//换行
rowNo++;
//获取第六行
nRow=sheet.getRow(rowNo++);
nCell=nRow.getCell();
nCell.setCellValue("");
nCell=nRow.getCell();
nCell.setCellValue("");
//下载
DownloadUtil dUtil=new DownloadUtil();
ByteArrayOutputStream os=new ByteArrayOutputStream();
wb.write(os);
dUtil.download(os, response, "测试单.xls");
os.flush();
os.close();
}
其中,"表单模板.xls"是提前设计维护好的excel,例如:

该模板放置路径,与代码中需要一致,例如存放地址为:

download.java工具类内容如下:
package cn.tf.jk.util; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse; public class DownloadUtil { /**
* @param filePath 要下载的文件路径
* @param returnName 返回的文件名
* @param response HttpServletResponse
* @param delFlag 是否删除文件
*/
protected void download(String filePath,String returnName,HttpServletResponse response,boolean delFlag){
this.prototypeDownload(new File(filePath), returnName, response, delFlag);
} /**
* @param file 要下载的文件
* @param returnName 返回的文件名
* @param response HttpServletResponse
* @param delFlag 是否删除文件
*/
protected void download(File file,String returnName,HttpServletResponse response,boolean delFlag){
this.prototypeDownload(file, returnName, response, delFlag);
} /**
* @param file 要下载的文件
* @param returnName 返回的文件名
* @param response HttpServletResponse
* @param delFlag 是否删除文件
*/
public void prototypeDownload(File file,String returnName,HttpServletResponse response,boolean delFlag){
// 下载文件
FileInputStream inputStream = null;
ServletOutputStream outputStream = null;
try {
if(!file.exists()) return;
response.reset();
//设置响应类型 PDF文件为"application/pdf",WORD文件为:"application/msword", EXCEL文件为:"application/vnd.ms-excel"。
response.setContentType("application/octet-stream;charset=utf-8"); //设置响应的文件名称,并转换成中文编码
//returnName = URLEncoder.encode(returnName,"UTF-8");
returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1")); //保存的文件名,必须和页面编码一致,否则乱码 //attachment作为附件下载;inline客户端机器有安装匹配程序,则直接打开;注意改变配置,清除缓存,否则可能不能看到效果
response.addHeader("Content-Disposition", "attachment;filename="+returnName); //将文件读入响应流
inputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
int length = ;
int readLength=;
byte buf[] = new byte[];
readLength = inputStream.read(buf, , length);
while (readLength != -) {
outputStream.write(buf, , readLength);
readLength = inputStream.read(buf, , length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
//删除原文件 if(delFlag) {
file.delete();
}
}
} /**
* by tony 2013-10-17
* @param byteArrayOutputStream 将文件内容写入ByteArrayOutputStream
* @param response HttpServletResponse 写入response
* @param returnName 返回的文件名
*/
public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException{
response.setContentType("application/octet-stream;charset=utf-8");
returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1")); //保存的文件名,必须和页面编码一致,否则乱码
response.addHeader("Content-Disposition", "attachment;filename=" + returnName);
response.setContentLength(byteArrayOutputStream.size()); ServletOutputStream outputstream = response.getOutputStream(); //取得输出流
byteArrayOutputStream.writeTo(outputstream); //写到输出流
byteArrayOutputStream.close(); //关闭
outputstream.flush(); //刷数据
}
}
前端调用:
var url = "newOrderCtrl/print";
postHref(url,param);//param是传输过去的参数,如果没有的话可以为空
jquery中postHref:
function postHref(url,param){
if(param && url){
var form = $("<form>"); //定义一个form表单
form.attr('style','display:none'); //在form表单中添加查询参数
form.attr('method','post');
form.attr('action',url);
var $param = $("<input type='text' name='param' />");
$param.attr('value',JSON.stringify(param));
form.append($param);
form.appendTo('body');
form.css('display','none');
form.submit();
}else{
console.log("url或param为空!");
return false;
}
}
参考地址:https://blog.csdn.net/sdksdk0/article/details/53393453
源码下载地址:https://github.com/sdksdk0/JK
使用apache的poi来实现数据导出到excel的功能——方式一的更多相关文章
- 使用apache的poi来实现数据导出到excel的功能——方式二
此次,介绍利用poi与layui table结合导出excel.这次不需要从数据库中查询出来的数据进行每一行的拼接那么麻烦,我们这次将标题定义一个id值,对应从数据库中查找出来的字段名即可. 1.po ...
- Java利用Apache POI将数据库数据导出为excel
将数据库中的数据导出为excel文件,供其他人查看 public class POITest { public static void main(String[] args) { POITest te ...
- 使用POI把查询到的数据表数据导出到Excel中,一个表一个sheet.最详细!!!
一.需求 我们会遇到开发任务: 经理:小王,你来做一下把数据库里的数据导出到Excel中,一个表是一个sheet,不要一个表一个Excel. 小王:好的,经理.(内心一脸懵逼) 二.前期准备 首先我们 ...
- struts2结合poi-3.7实现数据导出为excel
我们在处理数据的时候,有可能要将数据导出到excel文件中,那么java中是怎么实现的呢?apache开发的poi就可以帮我们实现啦,它也是开源的代码,导入相应的jar包,就可以轻松实现,下面让我们来 ...
- 大批量数据导出到Excel的实现
在平时的项目中,将数据导出到Excel的需求是很常见的,在此对一些常见的方法做以总结,并提供一种大数据量导出的实现. OLEDB 使用OLEDB可以很方便导出Excel,思路很简单,处理时将Exc ...
- 学习笔记 DataGridView数据导出为Excel
DataGridView数据导出为Excel 怎样把WinForm下的“DGV”里的绑定数据库后的数据导出到Excel中. 比如:在窗体里有个一“DGV”,DataGridView1,绑定了数据源 ...
- 将C1Chart数据导出到Excel
大多数情况下,当我们说将图表导出到Excel时,意思是将Chart当成图片导出到Excel中.如果是这样,你可以参考帮助文档中保存和导出C1Chart章节. 不过,也有另一种情况,当你想把图表中的数据 ...
- vb.net-三种将datagridview数据导出为excel文件的函数
第一种方法较慢,但是数据格式都比较好,需要引用excel的 Microsoft.Office.Interop.Excel.dll office.dll #Region "导出excel函数 ...
- 数据导出至Excel文件--好库编程网http://code1.okbase.net/codefile/SerializeHelper.cs_2012122018724_118.htm
using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; ...
随机推荐
- PyTorch : torch.nn.xxx 和 torch.nn.functional.xxx
PyTorch : torch.nn.xxx 和 torch.nn.functional.xxx 在写 PyTorch 代码时,我们会发现一些功能重复的操作,比如卷积.激活.池化等操作.这些操作分别可 ...
- poj1986 Distance Queries(lca又是一道模版题)
题目链接:http://poj.org/problem?id=1986 题意:就是老问题求val[u]+val[v]-2*val[root]就行.还有这题没有给出不联通怎么输出那么题目给出的数据一定 ...
- 解决flutter:unable to find valid certification path to requested target 的问题
1.问题 周末在家想搞搞flutter,家里电脑是windows的,按照官网教程一步步安装好以后,创建flutter工程,点击运行,一片红色弹出来,WTF? PKIX path building fa ...
- 什么是WSGI
WSGI全称为Python Web Server Gateway Interface,Python Web服务器网关接口,它是介于Web服务器和Web应用程序(或Web框架)之间的一种简单而通用的接口 ...
- VS Code 前端开发常用快捷键插件
一.vs code 的常用快捷键 1.注释:a) 单行注释:[ctrl+k,ctrl+c] 或 ctrl+/ b) 取消单行注释:[ctrl+k,ctrl+u] (按下ctrl不放,再按k + u) ...
- axios跨域访问eggjs的坑egg-cors egg-passport passport-local session传递问题
在同一机器上写前端和后端,前端使用webpack-dev-server启动,后端直接在eggjs项目目录下使用npm run dev启动,这种情况下,前端访问后端就是跨域访问.eggjs提供了一个跨域 ...
- Mysql 用户root密码重置
Asterisk安装完成之后,接手新的Asterisk系统后不清楚Mysql的root账号密码. 重新重置mysql的root密码的方式 先查看mysql的版本号. 我的测试环境下的mysql版本为5 ...
- spring security jquery ajax重定向问题解决
服务器端security增加一个配置如下: @Override protected void configure(HttpSecurity http) throws Exception { Strin ...
- 洛谷 P1181数列分段Section I
星爆气流(弃疗)斩! ——<刀剑神域> 题目:https://www.luogu.org/proble ...
- Spotlight on Oracle注册码破解(亲测可用)
了解到该工具监控十分强大,该工具优点: 我就是为了监控一个Oracle数据库,查阅各种资料,真是费了十牛二虎之力,才破解完成.#_# 在客户端安装好了,连接监控的服务器,提示得要注册码,这外国的软件基 ...