使用org.apache.poi导出Excel表格
public HSSFWorkbook MakeExcel(List<TransactionLogVO> logList) {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/*response.reset();
response.setHeader("Content-Disposition", "attachment;fileName="+ fileName);// 指定下载的文件名
OutputStream output = response.getOutputStream();
BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output); */
// String path = this.getClass().getClassLoader().getResource("WEB-INF/tqjsxx").getPath();
// 定义单元格报头
String worksheetTitle = "交易日志信息";
HSSFWorkbook wb = new HSSFWorkbook();
// 创建单元格样式
HSSFCellStyle cellStyleTitle = wb.createCellStyle();
// 指定单元格居中对齐
cellStyleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 指定单元格垂直居中对齐
cellStyleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 指定当单元格内容显示不下时不换行
cellStyleTitle.setWrapText(false);
// ------------------------------------------------------------------
HSSFCellStyle cellStyle = wb.createCellStyle();
// 指定单元格居中对齐
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 指定单元格垂直居中对齐
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 指定当单元格内容显示不下时换行
cellStyle.setWrapText(true);
// ------------------------------------------------------------------
// 设置单元格字体
HSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋体");
font.setFontHeight((short) 200);
cellStyleTitle.setFont(font);
// 工作表名
String id = "序号";
String channelCode = "渠道代码";
String channelName = "渠道名称";
String cityName = "所属城市";
String functionCode = "接口功能";
String logTime = "日志时间";
String reqMsgId = "消息ID";
String reqTime = "请求时间";
String reqMsg = "请求报文";
String respTime = "响应时间";
String resultCode = "处理代码";
String respMsg = "响应报文";
HSSFSheet sheet = wb.createSheet();
ExportExcel exportExcel = new ExportExcel(wb, sheet);
// 创建报表头部
exportExcel.createNormalHead(worksheetTitle, 11);
// 定义第一行
HSSFRow row1 = sheet.createRow(1);
HSSFCell cell1 = row1.createCell(0);
//第一行第1列
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(id));
sheet.setColumnWidth(0, 7 * 256);
//第一行第2列
cell1 = row1.createCell(1);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(channelCode));
//第一行第3列
cell1 = row1.createCell(2);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(channelName));
//第一行第4列
cell1 = row1.createCell(3);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(cityName));
//第一行第5列
cell1 = row1.createCell(4);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(functionCode));
sheet.setColumnWidth(4, 20 * 256);
//第一行第6列
cell1 = row1.createCell(5);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(logTime));
sheet.setColumnWidth(5, 20 * 256);
//第一行第7列
cell1 = row1.createCell(6);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(reqMsgId));
sheet.setColumnWidth(6, 20 * 256);
//第一行第8列
cell1 = row1.createCell(7);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(reqTime));
sheet.setColumnWidth(7, 20 * 256);
//第一行第9列
cell1 = row1.createCell(8);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(reqMsg));
sheet.setColumnWidth(8, 40 * 256);
//第一行第10列
cell1 = row1.createCell(9);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(respTime));
sheet.setColumnWidth(9, 20 * 256);
//第一行第11列
cell1 = row1.createCell(10);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(resultCode));
sheet.setColumnWidth(10, 20 * 256);
//第一行第12列
cell1 = row1.createCell(11);
cell1.setCellStyle(cellStyleTitle);
cell1.setCellValue(new HSSFRichTextString(respMsg));
sheet.setColumnWidth(11, 40 * 256);
//定义第二行开始后的实体内容
HSSFRow row = sheet.createRow(2);
HSSFCell cell = row.createCell(1);
for (int i = 0; i < logList.size(); i++) {
TransactionLogVO transactionLog = JSON.parseObject(JSONObject.toJSONString(logList.get(i)), TransactionLogVO.class);
row = sheet.createRow(i + 2);
cell = row.createCell(0);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString(transactionLog.getId() + ""));
cell = row.createCell(1);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString(transactionLog.getChannelCode()));
cell = row.createCell(2);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString(transactionLog.getChannelName()));
cell = row.createCell(3);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString(transactionLog.getCityName()));
cell = row.createCell(4);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString(transactionLog.getFunctionCode()));
cell = row.createCell(5);
cell.setCellStyle(cellStyle);
//cell.setCellValue(new HSSFRichTextString(sdf.format(transactionLog.getLogTime())));
cell.setCellValue(new HSSFRichTextString(timeStamp2Date(transactionLog.getLogTime())));
cell = row.createCell(6);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString(transactionLog.getReqMsgId()));
cell = row.createCell(7);
cell.setCellStyle(cellStyle);
//cell.setCellValue(new HSSFRichTextString(sdf.format(transactionLog.getReqTime())));
cell.setCellValue(new HSSFRichTextString(timeStamp2Date(transactionLog.getReqTime())));
cell = row.createCell(8);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString(transactionLog.getReqMsg()));
cell = row.createCell(9);
cell.setCellStyle(cellStyle);
//cell.setCellValue(new HSSFRichTextString(sdf.format(transactionLog.getRespTime())));
cell.setCellValue(new HSSFRichTextString(timeStamp2Date(transactionLog.getRespTime())));
cell = row.createCell(10);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString(transactionLog.getResultCode()));
cell = row.createCell(11);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString(transactionLog.getRespMsg()));
}
return wb;
}
导出表格工具类
public class ExportExcel {
private HSSFWorkbook wb = null;
private HSSFSheet sheet = null;
/**
* @param wb
* @param sheet
*/
public ExportExcel(HSSFWorkbook wb, HSSFSheet sheet) {
// super();
this.wb = wb;
this.sheet = sheet;
}
/**
* 创建通用EXCEL头部
*
* @param headString
* 头部显示的字符
* @param colSum
* 该报表的列数
*/
public void createNormalHead(String headString, int colSum) {
HSSFRow row = sheet.createRow(0);
// 设置第一行
HSSFCell cell = row.createCell(0);
// row.setHeight((short) 1000);
// 定义单元格为字符串类型
cell.setCellType(HSSFCell.ENCODING_UTF_16);// 中文处理
cell.setCellValue(new HSSFRichTextString(headString));
// 指定合并区域
/**
* public Region(int rowFrom, short colFrom, int rowTo, short colTo)
*/
sheet.addMergedRegion(new CellRangeAddress(0, (short) 0, (short) 0, (short) colSum));
// 定义单元格格式,添加单元格表样式,并添加到工作簿
HSSFCellStyle cellStyle = wb.createCellStyle();
// 设置单元格水平对齐类型
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐
cellStyle.setWrapText(true);// 指定单元格自动换行
// 设置单元格字体
HSSFFont font = wb.createFont();
// font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// font.setFontName("宋体");
// font.setFontHeight((short) 600);
// cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
}
/**
* 创建通用报表第二行
*
* @param params
* 统计条件数组
* @param colSum
* 需要合并到的列索引
*/
public void createNormalTwoRow(String[] params, int colSum) {
// 创建第二行
HSSFRow row1 = sheet.createRow(1);
row1.setHeight((short) 400);
HSSFCell cell2 = row1.createCell(0);
cell2.setCellType(HSSFCell.ENCODING_UTF_16);
cell2.setCellValue(new HSSFRichTextString("时间:" + params[0] + "至"
+ params[1]));
// 指定合并区域
/**
* public Region(int rowFrom, short colFrom, int rowTo, short colTo)
*/
sheet.addMergedRegion(new CellRangeAddress(1, 1, (short) 0, (short) colSum));
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐
cellStyle.setWrapText(true);// 指定单元格自动换行
// 设置单元格字体
HSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋体");
font.setFontHeight((short) 250);
cellStyle.setFont(font);
cell2.setCellStyle(cellStyle);
}
/**
* 设置报表标题
*
* @param columHeader
* 标题字符串数组
*/
public void createColumHeader(String[] columHeader) {
// 设置列头 在第三行
HSSFRow row2 = sheet.createRow(2);
// 指定行高
row2.setHeight((short) 600);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐
cellStyle.setWrapText(true);// 指定单元格自动换行
// 单元格字体
HSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋体");
font.setFontHeight((short) 250);
cellStyle.setFont(font);
// 设置单元格背景色
cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
HSSFCell cell3 = null;
for (int i = 0; i < columHeader.length; i++) {
cell3 = row2.createCell(i);
cell3.setCellType(HSSFCell.ENCODING_UTF_16);
cell3.setCellStyle(cellStyle);
cell3.setCellValue(new HSSFRichTextString(columHeader[i]));
}
}
/**
* 创建内容单元格
*
* @param wb
* HSSFWorkbook
* @param row
* HSSFRow
* @param col
* short型的列索引
* @param align
* 对齐方式
* @param val
* 列值
*/
public void cteateCell(HSSFWorkbook wb, HSSFRow row, int col, short align,
String val) {
HSSFCell cell = row.createCell(col);
cell.setCellType(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(new HSSFRichTextString(val));
HSSFCellStyle cellstyle = wb.createCellStyle();
cellstyle.setAlignment(align);
cell.setCellStyle(cellstyle);
}
/**
* 创建合计行
*
* @param colSum
* 需要合并到的列索引
* @param cellValue
*/
public void createLastSumRow(int colSum, String[] cellValue) {
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐
cellStyle.setWrapText(true);// 指定单元格自动换行
// 单元格字体
HSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋体");
font.setFontHeight((short) 250);
cellStyle.setFont(font);
// 获取工作表最后一行
HSSFRow lastRow = sheet.createRow((short) (sheet.getLastRowNum() + 1));
HSSFCell sumCell = lastRow.createCell(0);
sumCell.setCellValue(new HSSFRichTextString("合计"));
sumCell.setCellStyle(cellStyle);
// 合并 最后一行的第零列-最后一行的第一列
sheet.addMergedRegion(new CellRangeAddress(sheet.getLastRowNum(), sheet.getLastRowNum(),
(short) 0, (short) colSum));// 指定合并区域
for (int i = 2; i < (cellValue.length + 2); i++) {
// 定义最后一行的第三列
sumCell = lastRow.createCell(i);
sumCell.setCellStyle(cellStyle);
// 定义数组 从0开始。
sumCell.setCellValue(new HSSFRichTextString(cellValue[i - 2]));
}
}
/**
* 输入EXCEL文件
*
* @param fileName
* 文件名
*/
public void outputExcel(String fileName) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(fileName));
wb.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @return the sheet
*/
public HSSFSheet getSheet() {
return sheet;
}
/**
* @param sheet
* the sheet to set
*/
public void setSheet(HSSFSheet sheet) {
this.sheet = sheet;
}
/**
* @return the wb
*/
public HSSFWorkbook getWb() {
return wb;
}
/**
* @param wb
* the wb to set
*/
public void setWb(HSSFWorkbook wb) {
this.wb = wb;
}
}
调用方法
@RequestMapping("/export")
public void export(TransactionLogVO transactionlog, HttpServletRequest request, HttpServletResponse response) {
ResultMessage<DataGridVO> queryRs = transactionLogServiceImpl.list(transactionlog);
//System.out.println(queryRs.toString());
//Map<?, ?> resultMap = JSON.parseObject(queryRs.toString());
List<TransactionLogVO> resultL = new ArrayList<TransactionLogVO>();
//if ((Integer) resultMap.get("errcode") == 0) {
resultL = (List<TransactionLogVO>) queryRs.getObj().getRows();
// }
if (resultL == null || resultL.size() == 0) {
resultL = new ArrayList<TransactionLogVO>();
}
System.out.println("resultL:" + resultL.toString());
HSSFWorkbook wb = MakeExcel(resultL);
String fileName = "交易日志.xls";
try {
fileName = new String(fileName.getBytes("utf-8"), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("fileName:" + fileName);
response.reset();
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);// 指定下载的文件名
response.setContentType("application/vnd.ms-excel;charset=utf-8");
try {
OutputStream output = response.getOutputStream();
wb.write(output);
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
需要在pom文件加入POI依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10.1</version>
</dependency>
使用org.apache.poi导出Excel表格的更多相关文章
- Apache POI导出excel表格
项目中我们经常用到导出功能,将数据导出以便于审查和统计等.本文主要使用Apache POI实现导出数据. POI中文文档 简介 ApachePOI是Apache软件基金会的开放源码函式库,POI提供A ...
- 使用Apache POI导出Excel小结--导出XLS格式文档
使用Apache POI导出Excel小结 关于使用Apache POI导出Excel我大概会分三篇文章去写 使用Apache POI导出Excel小结--导出XLS格式文档 使用Apache POI ...
- apache poi导出excel报表
Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能.POI为"P ...
- java中使用poi导出excel表格数据并且可以手动修改导出路径
在我们开发项目中,很多时候会提出这样的需求:将前端的某某数据以excel表格导出,今天就给大家写一个简单的模板. 这里我们选择使用poi导出excel: 第一步:导入需要的jar包到 lib 文件夹下
- 使用poi导出Excel表格,jar包冲突
HTTP Status 500 – Internal Server Error Type Exception Report Message Handler processing failed; nes ...
- 复杂的POI导出Excel表格(多行表头、合并单元格)
poi导出excel有两种方式: 第一种:从无到有的创建整个excel,通过HSSFWorkbook,HSSFSheet HSSFCell, 等对象一步一步的创建出工作簿,sheet,和单元格,并添加 ...
- apache POI 导出excel相关方法
apache POI 操作excel无比强大.同时有操作word和ppt的接口. 下面讲解poi中常用方法. 1,设置列宽 HSSFSheet sheet = wb.getSheetAt(0); sh ...
- Apache POI导出excel
public String exportXls(HttpServletRequest request, HttpServletResponse response) { try { HSSFWorkbo ...
- poi导出excel表格
package poiexcel; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; ...
随机推荐
- Windows10状态栏右下角的上升三角号没有了
闲着没事装了360和电脑管家,捣鼓了下里面的功能,好像是弄了桌面整理和主题之后出现了这个问题,刚开始还以为因为清理卸载软件把系统的这项功能给卸载了,其实原因很简单,相信看完解决这个问题的方案你就明白了 ...
- 每天一个小程序—0014题(txt 转 Excel)
基础知识:Excel文件的后缀有xls和xlsx,前者是针对2003版本的,2007及其之后的版本是xlsx. 在python中对于这两种不同后缀的文件有不同的库来处理,对于xls用wlrd.xlwt ...
- Python Scrapy安装
直接安装scrapy 各种报错,后来各种百度终于解决了,如下是亲身的经历. pip install scrapy 这样直接会报错. 第一步: 先安装wheel pip install wheel 第二 ...
- [从零开始搭网站六]为域名申请免费SSL证书(https),并为Tomcat配置https域名所用的多SSL证书
点击下面连接查看从零开始搭网站全系列 从零开始搭网站 由于国内的网络环境比较恶劣,运营商流量劫持的情况比较严重,一般表现为别人打开你的网站的时候会弹一些莫名其妙的广告...更过分的会跳转至别的网站. ...
- 进度条的制作-python
import time,sys def view_bar(num, total): rate = float(num) / float(total) rate_num = int(rate * 100 ...
- 【Python】【进程&线程】
#[[进程 和 线程 ]] """ # [多进程]'''import os print ('Process (%s) start...' % os.getpid()) # ...
- MongoDB 对象操作
对象插入 >db.col.insert({title: 'MongoDB 教程', description: 'MongoDB 是一个 Nosql 数据库', by: 'xxx', url: ' ...
- Jmeter 二次开发 将CSV Data Set Config添加从哪一行开始读数据
经常遇到性能测试的时候,有100万条数据,才用了5万条,中途因为某些原因停止了,继续用的时候, 要么要清除DB中数据,要么要清除数据源中的数据, 觉得特别麻烦, 希望改写下代码,将 Ignore fi ...
- str_replace 批量查找替换字符串
<?php $str = 'I Love You!'; $str = str_replace('o','O',$str,$count); echo $str.PHP_EOL; // I LOve ...
- requests:json请求中中文乱码处理
requests库中,在处理json格式的请求时调用的json.dumps方法参数ensure_ascii默认为True.表示序列化时对中文默认使用的ascii编码.如果想要显示中文,则将此参数的值改 ...