Maven项目结合POI导出Excl表格

一、POM文件添加依赖

 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>

二、将ExportExcel类放进项目的util中

package com.jonychen.util.core;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List; import static com.jonychen.HttpKit.getResponse;(后面有代码,复制粘贴即可)
/**
*导出工具类
*/
public class ExportExcel{ //显示的导出表的标题
private String title;
//导出表的列名
private String[] rowName ; private List<Object[]> dataList = new ArrayList<Object[]>(); HttpServletResponse response; //构造方法,传入要导出的数据
public ExportExcel(String title,String[] rowName,List<Object[]> dataList){
this.dataList = dataList;
this.rowName = rowName;
this.title = title;
} /*
* 导出数据
* */
public void export() throws Exception{
try{
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
HSSFSheet sheet = workbook.createSheet(title); // 创建工作表 // 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0); //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象 sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(title); // 定义所需列数
int columnNum = rowName.length;
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行) // 将列头设置到sheet的单元格中
for(int n=0;n<columnNum;n++){
HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
cellRowName.setCellValue(text); //设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
} //将查询出的数据设置到sheet对应的单元格中
for(int i=0;i<dataList.size();i++){ Object[] obj = dataList.get(i);//遍历每个对象
HSSFRow row = sheet.createRow(i+3);//创建所需的行数 for(int j=0; j<obj.length; j++){
HSSFCell cell = null; //设置单元格的数据类型
if(j == 0){
cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(i+1);
}else{
cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
if(!"".equals(obj[j]) && obj[j] != null){
cell.setCellValue(obj[j].toString()); //设置单元格的值
}
}
cell.setCellStyle(style); //设置单元格样式
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
if(colNum == 0){
sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
}else{
sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
}
} if(workbook !=null){
try
{
String fileName = "Excel-Signup" + System.currentTimeMillis() + ".xls";
String headStr = "attachment; filename=\"" + fileName + "\"";
response =getResponse();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
OutputStream out = response.getOutputStream();
workbook.write(out);
}
catch (IOException e)
{
e.printStackTrace();
}
} }catch(Exception e){
e.printStackTrace();
} } /*
* 列头单元格样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) { // 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; } /*
* 列数据信息单元格样式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; }
}
com.jonychen.HttpKit.getResponse
/**
* Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jonychen.util.core; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class HttpKit { public static String getIp(){
return HttpKit.getRequest().getRemoteHost();
} /**
* 获取所有请求的值
*/
public static Map<String, String> getRequestParameters() {
HashMap<String, String> values = new HashMap<>();
HttpServletRequest request = HttpKit.getRequest();
Enumeration enums = request.getParameterNames();
while ( enums.hasMoreElements()){
String paramName = (String) enums.nextElement();
String paramValue = request.getParameter(paramName);
values.put(paramName, paramValue);
}
return values;
} /**
* 获取 HttpServletRequest
*/
public static HttpServletResponse getResponse() {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
return response;
} /**
* 获取 包装防Xss Sql注入的 HttpServletRequest
* @return request
*/
public static HttpServletRequest getRequest() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return new WafRequestWrapper(request);
} /**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, Map<String, String> param) {
String result = "";
BufferedReader in = null;
try {
String para = "";
for (String key : param.keySet()) {
para += (key + "=" + param.get(key) + "&");
}
if (para.lastIndexOf("&") > 0) {
para = para.substring(0, para.length() - 1);
}
String urlNameString = url + "?" + para;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
//for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
//}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
} /**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String, String> param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
String para = "";
for (String key : param.keySet()) {
para += (key + "=" + param.get(key) + "&");
}
if (para.lastIndexOf("&") > 0) {
para = para.substring(0, para.length() - 1);
}
String urlNameString = url + "?" + para;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
} }

三、项目中写Controller逻辑层进行调用工具类导出即可

    @RequestMapping(value = "/export",method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
@ApiOperation(value = "导出报表", httpMethod = "GET", notes = "导出报表,前端写一个导出地址调用此接口即可")
public void signupExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
//获取数据
List<SignupInfo> list = signupService.getSignupList();
logger.info("获取全部列表数据"+JSONArray.toJSON(list)); String title = "汇总表";
String[] rowsName = new String[]{"序号", "姓名", "性别","手机号码", "单位名称", "省", "备注"};
List<Object[]> dataList = new ArrayList<>();
Object[] objs = null;
for (int i = 0; i < list.size(); i++) {
SignupfdfdsInfo signupInfo= list.get(i);
objs = new Object[rowsName.length];
objs[0] = signupInfo.getId();
objs[1] = signupInfo.getUserName();
objs[2] = signupInfo.getSex();
objs[3]=signupInfo.getMobile();
objs[4] = signupInfo.getCompany();
objs[5] = signupInfo.getProvince();
objs[6] = signupInfo.getRemark();
dataList.add(objs);
}
ExportExcel ex = new ExportExcel(title, rowsName, dataList);
ex.export();
}

可能遇到的异常:NPE(原因:导出的数据中没有值,数据库中存的值都要有默认值,我varchar型存的是无,int型的是0)

Maven项目结合POI导出Excl表格Demo-亲测可用的更多相关文章

  1. 解决Eclipse左键无法查看maven第三方包的源代码,多图亲测可用【转】

    Debug进不了的原因及解决办法: 一.ctrl+左键点击没有找到你的源码 1.先设置maven 2.通过maven下Jar包源码 选中总包目录下的pom.xml-->右键-->Run A ...

  2. Maven项目结合POI实现导入导入导入导入导入Excl表格Demo-亲测可用

    第一步:写入maven依赖(3.6是比较稳定的版本,可用于生产环境) <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --& ...

  3. poi导出word表格详解 超详细了

    转:非常感谢原作者 poi导出word表格详解 2018年07月20日 10:41:33 Z丶royAl 阅读数:36138   一.效果如下 二.js代码 function export_word( ...

  4. java中使用poi导出excel表格数据并且可以手动修改导出路径

    在我们开发项目中,很多时候会提出这样的需求:将前端的某某数据以excel表格导出,今天就给大家写一个简单的模板. 这里我们选择使用poi导出excel: 第一步:导入需要的jar包到 lib 文件夹下

  5. 使用poi导出Excel表格,jar包冲突

    HTTP Status 500 – Internal Server Error Type Exception Report Message Handler processing failed; nes ...

  6. 复杂的POI导出Excel表格(多行表头、合并单元格)

    poi导出excel有两种方式: 第一种:从无到有的创建整个excel,通过HSSFWorkbook,HSSFSheet HSSFCell, 等对象一步一步的创建出工作簿,sheet,和单元格,并添加 ...

  7. poi导出word表格跨行

    DataCommon.java package com.ksource.pwlp.model.statistic; public class DataCommon { private Long id; ...

  8. Strust2+POI导出exel表格且解决文件名中文乱码/不显示

    下载并导入项目[poi.3.17.jar] strust.xml <action name="returnLate_*" class="com.stureturnl ...

  9. windows下的java项目打jar分别编写在windows与linux下运行的脚本( 本人亲测可用!)

    前言: 最近公司做了一个工具,要将这个工具打包成一个可运行的程序,编写start.bat和start.sh在windows和linux下都可以运行. 在网上找了很多资料,最后终于找到一个可靠的资料,记 ...

随机推荐

  1. property staticmathod classmethod 反射

    使用@property 在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改: s = Student() s.score = 9999 这显然不合逻 ...

  2. 51Nod1962 区间计数

    这题与之前那道区间最值的题非常类似,依旧是二分区间,然后统计跨过中间点的区间贡献. 我们要选出小于等于和小于的,这样就可以算出相等的区间长了. 复杂度O(nlogn) By:大奕哥 #include& ...

  3. [待码][BZOJ1858]SCOI2010序列操作 jzyzoj1655

    待码的线段树.....太长了看上去不是很想写 [ 什么破理由啊摔,不要脸 ] 嗯先水几道再写

  4. VK Cup 2016 - Round 1 (Div. 2 Edition) B. Bear and Displayed Friends 树状数组

    B. Bear and Displayed Friends 题目连接: http://www.codeforces.com/contest/658/problem/B Description Lima ...

  5. 求助下 Ubuntu 15.10(64 位)下安装 pyspider 下的问题 - V2EX

    https://www.v2ex.com/t/279405 求助下 Ubuntu 15.10(64 位)下安装 pyspider 下的问题 - V2EX pip 更新到最新 sudo apt inst ...

  6. Two-transistor circuit replaces IC

    Linear Technology's recently introduced LTC4300 chip buffers I2C clock and data lines to and from a ...

  7. Use two picogate devices for bidirectional level-shifting

    In new mixed-voltage systems, it is often necessary to level-shift a control signal from a high leve ...

  8. 自己定义AlertDialog对话框布局

    自己定义对话框中的信息body布局 LayoutInflater inflater =getLayoutInflater(); View layout = inflater.inflate(R.lay ...

  9. 关于npm run build 卡住不动的坑。。。

    起因:最近开发个项目使用的vue,有些功能需要生产版本放服务器上测试,这就出问题了..卡住了,不动了,还不报错 这是在vscode的终端里面,试了git hash,试了cmd , 试了powershe ...

  10. cocos2d-x hello world及安卓平台迁移

        本节和大家一起新建一个项目工程,并通过cygwin迁移至android平台.      以下是本节主要内容: 利用cocos2d-x自带脚本,生成测试工程,并测试运行: 将该测试项目通过cyg ...