POIExcelUtils.java:

package com.saicfc.pmpf.internal.manage.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import com.saicfc.pmpf.common.enums.ChannelCodeEnums; /**
* @author lizhiyong
* @version $Id: POIExcelUtils.java, v 0.1
2014年9月18日 上午9:28:30 Exp $
*/
public class POIExcelUtils { /**
* 定制日期格式
*/
private static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /**
* 定制浮点数格式
*/
private static String NUMBER_FORMAT = "#,##0.00"; /**
* 定制百分比格式
*/
private static String PRECENT_FORMAT = "0.00%"; private static HSSFWorkbook workbook = new HSSFWorkbook(); private static HSSFSheet sheet = workbook.createSheet(); private static HSSFRow row; /**
* 导出Excel文件
* @param filePath
* @throws IOException
*/
public static void exportXLS(String filePath) throws IOException {
try {
FileOutputStream fOut = new FileOutputStream(filePath);
workbook.write(fOut);
fOut.flush();
fOut.close();
} catch (IOException e) {
e.getStackTrace();
}
} /**
* 导出Excel文件
* @param file
* @throws IOException
*/
public static void exportXLS(File file) throws IOException {
try {
FileOutputStream fOut = new FileOutputStream(file);
workbook.write(fOut);
fOut.flush();
fOut.close();
} catch (IOException e) {
e.getStackTrace();
}
} /**
* 添加一行
* @param index 行号
*/
public static void createRow(int index) {
row = sheet.createRow(index);
} /**
* 设置单元格的字符值格式
* @param index 列号
* @param value 单元格填充的值
*/
public static void setStringCell(int index, String value) {
HSSFCell cell = row.createCell(index);
cell.setCellValue(value);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
} /**
* 设置单元格日期格式
* @param index 列号
* @param value 单元格填充值
*/
public static void setDateCell(int index, Calendar value) {
HSSFCell cell = row.createCell(index);
cell.setCellValue(value.getTime());
//建立新的cell样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFDataFormat format = workbook.createDataFormat();
//设置cell样式为定制的日期格式
cellStyle.setDataFormat(format.getFormat(DATE_FORMAT));
//居中
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置该cell日期的显示格式
cell.setCellStyle(cellStyle);
} /**
* 设置单元格整数數值格式
* @param index 列号
* @param value 单元格填充值
*/
public static void setIntCell(int index, int value) {
HSSFCell cell = row.createCell(index);
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(value);
} /**
* 设置单元格浮点数值格式
* @param index 列号
* @param value 单元格填充值
*/
public static void setNumberCell(int index, double value) {
HSSFCell cell = row.createCell(index);
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(value);
//建立新的cell样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFDataFormat format = workbook.createDataFormat();
//设置cell样式为定制的浮点数格式
cellStyle.setDataFormat(format.getFormat(NUMBER_FORMAT));
//设置该cell浮点数的显示格式
cell.setCellStyle(cellStyle);
} /**
* 设置单元格百分比格式
* @param index 列号
* @param value 单元格填充值
*/
public static void setPercentCell(int index, double value) {
HSSFCell cell = row.createCell(index);
cell.setCellValue(value);
//建立新的cell样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFDataFormat format = workbook.createDataFormat();
cellStyle.setDataFormat(format.getFormat(PRECENT_FORMAT));
cell.setCellStyle(cellStyle);
} public static void main(String[] args) {
System.out.println(" 開始导出Excel文件 ");
createRow(0);
setStringCell(0, " 编号 ");
setStringCell(1, " 名称 ");
setStringCell(2, " 日期 ");
setStringCell(3, " 金额 ");
createRow(1);
setIntCell(0, 1);
setStringCell(1, " 工商银行 ");
setDateCell(2, Calendar.getInstance());
setNumberCell(3, 111123.99);
createRow(2);
setIntCell(0, 2);
setStringCell(1, " 招商银行 ");
setDateCell(2, Calendar.getInstance());
setNumberCell(3, 222456.88);
try {
String filePath = "C:/lizhiyong.xls";
exportXLS(filePath);
System.out.println(" 导出Excel文件[成功] ");
} catch (IOException e1) {
System.out.println(" 导出Excel文件[失败] ");
e1.printStackTrace();
}
} /**
* 生成一个Excel文件POI
* @param inputFile 输入模板文件路径
* @param outputFile 输入文件存放于server路径
* @param dataList 待导出数据
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public static File exportExcelFile(String channelCode, String filePath, List titleList,
List dataList, String fileName) throws Exception {
File file = new File(filePath);
if (!file.exists()) {
file.mkdir();
System.out.println("目录已创建");
}
if (ChannelCodeEnums.PINGAN.getChannelCode().equals(channelCode)) {
//设置列宽
sheet.setColumnWidth(0, 5000);
sheet.setColumnWidth(1, 4000);
sheet.setColumnWidth(2, 8000);
}
//定义文件名称格式并创建
File excelFile = File.createTempFile(fileName, ".xls", new File(filePath));
//加入头信息
int row = 0;
for (Iterator iterator = titleList.iterator(); iterator.hasNext();) {
LinkedHashMap titleMap = (LinkedHashMap) iterator.next();
//新增一行
createRow(row);
int cell = 0;
for (Iterator titleIterator = titleMap.entrySet().iterator(); titleIterator.hasNext();) {
java.util.Map.Entry titleEntry = (java.util.Map.Entry) titleIterator.next();
//向列中加入值
setStringCell(cell, (String) titleEntry.getValue());
cell++;
}
row++;
} //以下開始加入单元格信息
int rows = titleList.size();
for (Iterator iterator = dataList.iterator(); iterator.hasNext();) {
LinkedHashMap dataMap = (LinkedHashMap) iterator.next();
//新增一行
createRow(rows);
int cells = 0;
for (Iterator dataIterator = dataMap.entrySet().iterator(); dataIterator.hasNext();) {
java.util.Map.Entry dataEntry = (java.util.Map.Entry) dataIterator.next();
if (ChannelCodeEnums.PINGAN.getChannelCode().equals(channelCode)) {
if ("refChannelOrderNo".equals(dataEntry.getKey())) {
//向列中加入值
setStringCell(cells, (String) dataEntry.getValue());
} else if ("amount".equals(dataEntry.getKey())) {
//向列中加入浮点型数值
setNumberCell(cells, Double.parseDouble((String) dataEntry.getValue()));
} else {
//向列中加入值
setStringCell(cells, (String) dataEntry.getValue());
}
} else {
//向列中加入值
setStringCell(cells, (String) dataEntry.getValue());
}
cells++;
}
rows++;
} exportXLS(excelFile);
return excelFile;
}
}

以下是调用:

 String fileName = "平安银行(PINGAN)退款数据";
List titleList = new ArrayList();
LinkedHashMap titleMap = new LinkedHashMap();
titleMap.put("title1", "订单号");
titleMap.put("title2", "退款金额");
titleMap.put("title3", "退款原因");
titleList.add(0, titleMap);
File file;
try {
file = POIExcelUtils.exportExcelFile(channelCode, filePath, titleList, exportData,
fileName);
//下载文件
downLoadFile(response, filePath, file);
} catch (Exception e) {
log.error("下载失败", e);
}
  /**
* 下载文件
* @param response
* @param filePath 文件路径
* @param file 文件
* @throws IOException
*/
public void downLoadFile(HttpServletResponse response, String filePath, File file)
throws IOException {
String fileName = file.getName();
//下载文件
FileManageUtils.exportFile(response, filePath + fileName, fileName);
//删除单个文件
FileManageUtils.deleteFile(filePath, fileName);
}
package com.saicfc.pmpf.internal.manage.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import javax.servlet.http.HttpServletResponse; /**
* 文件管理
* @author lizhiyong
* @version $Id: FileManageUtils.java, v 0.1
2014年9月11日 上午9:37:47 Exp $
*/
public class FileManageUtils { /**
* 下载文件
* @param response
* @param csvFilePath
* 文件路径
* @param fileName
* 文件名
* @throws IOException
*/
public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName)
throws IOException {
response.setContentType("application/csv;charset=GBK");
response.setHeader("Content-Disposition",
"attachment; filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
//URLEncoder.encode(fileName, "GBK") InputStream in = null;
try {
in = new FileInputStream(csvFilePath);
int len = 0;
byte[] buffer = new byte[1024];
response.setCharacterEncoding("GBK");
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
//out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
out.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
System.out.println(e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
} /**
* 删除该文件夹filePath下的全部文件
* @param filePath
* 文件文件夹路径
*/
public static void deleteFiles(String filePath) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
files[i].delete();
}
}
}
} /**
* 删除单个文件
* @param filePath
* 文件文件夹路径
* @param fileName
* 文件名
*/
public static void deleteFile(String filePath, String fileName) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
if (files[i].getName().equals(fileName)) {
files[i].delete();
return;
}
}
}
}
}
}

版权声明:本文博客原创文章,博客,未经同意,不得转载。

使用POI创建Excel文件下载的更多相关文章

  1. Java Struts2 POI创建Excel文件并实现文件下载

    Java Struts2 POI创建Excel文件并实现文件下载2013-09-04 18:53 6059人阅读 评论(1) 收藏 举报 分类: Java EE(49) Struts(6) 版权声明: ...

  2. Struts2使用POI创建Excel并下载

    本文将讲解在Struts2框架下如何使用POI创建Office Excel文档并实现下载功能. Apache POI ,操作微软文档的Java API,简单来说就是可以用来操作Office文档的API ...

  3. java使用poi创建excel文件

    import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFRow;import or ...

  4. java POI创建Excel示例(xslx和xsl区别 )

    Java用来处理office类库有很多,其中POI就是比较出名的一个,它是apache的类库,现在版本到了3.10,也就是2014年2月8号这个版本. 在处理PPT,Excel和Word前,需要导入以 ...

  5. POI创建Excel使用的常见的属性

    public static void main(String[] args) { //创建新的Excel 工作簿 HSSFWorkbook workbook =new HSSFWorkbook(); ...

  6. poi创建excel文件

    package com.mozq.sb.file01.test; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf. ...

  7. poi 创建excel数据

    public static void main(String[] args) throws Exception { // TODO 设置excel的标题 List<String> exce ...

  8. Java通过poi创建Excel文件并分页追加数据

    以下的main函数,先生成一个excel文件,并设置sheet的名称,设置excel头:而后,以分页的方式,向文件中追加数据 maven依赖 <dependency> <groupI ...

  9. 使用Apache下poi创建和读取excel文件

    一:使用apache下poi创建excel文档 @Test /* * 使用Apache poi创建excel文件 */ public void testCreateExcel() { // 1:创建一 ...

随机推荐

  1. 1297 - Largest Box(三分)

    1297 - Largest Box   PDF (English) Statistics Forum Time Limit: 2 second(s) Memory Limit: 32 MB In t ...

  2. 历时一年,我的著作《第一行代码——Android》已出版!

    前言 事实上我当初决定開始写博客的想法挺简单的,认为自己搞技术这么多年了,总应该要留下点什么.既然没能写出什么出色的应用,那至少也要留下点文字分享给大家,以指引在我后面的开发人员们,毕竟我也从前辈们的 ...

  3. 《数据通信与网络》笔记--虚电路网络:帧中继和ATM

    在之前的文章中已经介绍过虚电路交换,详细请参见:http://blog.csdn.net/todd911/article/details/9069447 这边介绍下使用虚电路交换的2中WAN技术:帧中 ...

  4. Identifiers

    Identifier An identifier is an arbitrarily long sequence of digits, underscores, lowercase and upper ...

  5. js 实现图片间隔循环轮播以及没有间隔的循环轮播

    链接地址:http://blog.sina.com.cn/s/blog_75cf5f32010199dn.html 最近做了个图片循环轮播的功能.就是几张图片不断的循环滚动显示. 感觉这个方法不错所以 ...

  6. CodeForces 260A Adding Digits

    这道题目的意思是给你提供a, b, n 三个数 a为 输入的数字 ,你需要在a后面加n次 ,每次可以加0-9 但要保证每次加上去的那个数字能被b整除 不过数据规模有点大,用搜索会MLE(即使开了个开栈 ...

  7. 基于visual Studio2013解决C语言竞赛题之0521圆盘求和

     题目

  8. #AzureChat - 自动伸缩和虚拟机

    我们很高兴地推出再一次 #AzureChat,这是 @WindowsAzure 团队为您精心打造的一个在 Twitter 上进行的聊天活动! #AzureChat 专注于云计算的各个方面以及云开发的最 ...

  9. 汉高澳大利亚sinox为什么不能下载源代码,因为sinox执行unix/linux/windows规划

    中国用户下载真正的澳大利亚sinox说完后sinox没有下载源代码. 这意味着,类似linux如下载linux 开源安装. 要知道.sinox并非linux. 首先,sinox是商业操作系统,就像 w ...

  10. C++逗号运算符与逗号表达式

    C++将赋值表达式作为表达式的一种,使赋值操作不仅可以出现在赋值语句中,而且可以以表达式形式出现在其他语句(如输出语句.循环语句等)中.这是C++语言灵活性的一种表现. 请注意,用cout语句输出一个 ...