package poiexcel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress; public class PoiExcelExport {
HttpServletResponse response;
// 文件名
private String fileName ;
//文件保存路径
private String fileDir;
//sheet名
private String sheetName;
//表头字体
private String titleFontType = "Arial Unicode MS";
//表头背景色
private String titleBackColor = "C1FBEE";
//表头字号
private short titleFontSize = 12;
//添加自动筛选的列 如 A:M
private String address = "";
//正文字体
private String contentFontType = "Arial Unicode MS";
//正文字号
private short contentFontSize = 12;
//Float类型数据小数位
private String floatDecimal = ".00";
//Double类型数据小数位
private String doubleDecimal = ".00";
//设置列的公式
private String colFormula[] = null; DecimalFormat floatDecimalFormat=new DecimalFormat(floatDecimal);
DecimalFormat doubleDecimalFormat=new DecimalFormat(doubleDecimal); private HSSFWorkbook workbook = null; public PoiExcelExport(String fileDir,String sheetName){
this.fileDir = fileDir;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
} public PoiExcelExport(HttpServletResponse response,String fileName,String sheetName){
this.response = response;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
}
/**
* 设置表头字体.
* @param titleFontType
*/
public void setTitleFontType(String titleFontType) {
this.titleFontType = titleFontType;
}
/**
* 设置表头背景色.
* @param titleBackColor 十六进制
*/
public void setTitleBackColor(String titleBackColor) {
this.titleBackColor = titleBackColor;
}
/**
* 设置表头字体大小.
* @param titleFontSize
*/
public void setTitleFontSize(short titleFontSize) {
this.titleFontSize = titleFontSize;
}
/**
* 设置表头自动筛选栏位,如A:AC.
* @param address
*/
public void setAddress(String address) {
this.address = address;
}
/**
* 设置正文字体.
* @param contentFontType
*/
public void setContentFontType(String contentFontType) {
this.contentFontType = contentFontType;
}
/**
* 设置正文字号.
* @param contentFontSize
*/
public void setContentFontSize(short contentFontSize) {
this.contentFontSize = contentFontSize;
}
/**
* 设置float类型数据小数位 默认.00
* @param doubleDecimal 如 ".00"
*/
public void setDoubleDecimal(String doubleDecimal) {
this.doubleDecimal = doubleDecimal;
}
/**
* 设置doubel类型数据小数位 默认.00
* @param floatDecimalFormat 如 ".00
*/
public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) {
this.floatDecimalFormat = floatDecimalFormat;
}
/**
* 设置列的公式
* @param colFormula 存储i-1列的公式 涉及到的行号使用@替换 如A@+B@
*/
public void setColFormula(String[] colFormula) {
this.colFormula = colFormula;
}
/**
* 写excel.
* @param titleColumn 对应bean的属性名
* @param titleName excel要导出的表名
* @param titleSize 列宽
* @param dataList 数据
*/
public void wirteExcel(String titleColumn[],String titleName[],int titleSize[],List<?> dataList){
//添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
Sheet sheet = workbook.createSheet(this.sheetName);
//新建文件
OutputStream out = null;
try {
if(fileDir!=null){
//有文件路径
out = new FileOutputStream(fileDir);
}else{
//否则,直接写到输出流中
out = response.getOutputStream();
fileName = fileName+".xls";
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(fileName, "UTF-8"));
} //写入excel的表头
Row titleNameRow = workbook.getSheet(sheetName).createRow(0);
//设置样式
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType, (short) titleFontSize);
titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short)10); for(int i = 0;i < titleName.length;i++){
sheet.setColumnWidth(i, titleSize[i]*256); //设置宽度
Cell cell = titleNameRow.createCell(i);
cell.setCellStyle(titleStyle);
cell.setCellValue(titleName[i].toString());
} //为表头添加自动筛选
if(!"".equals(address)){
CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address);
sheet.setAutoFilter(c);
} //通过反射获取数据并写入到excel中
if(dataList!=null&&dataList.size()>0){
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType, (short) contentFontSize); if(titleColumn.length>0){
for(int rowIndex = 1;rowIndex<=dataList.size();rowIndex++){
Object obj = dataList.get(rowIndex-1); //获得该对象
Class clsss = obj.getClass(); //获得该对对象的class实例
Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
for(int columnIndex = 0;columnIndex<titleColumn.length;columnIndex++){
String title = titleColumn[columnIndex].toString().trim();
if(!"".equals(title)){ //字段不为空
//使首字母大写
String UTitle = Character.toUpperCase(title.charAt(0))+ title.substring(1, title.length()); // 使其首字母大写;
String methodName = "get"+UTitle; // 设置要执行的方法
Method method = clsss.getDeclaredMethod(methodName); //获取返回类型
String returnType = method.getReturnType().getName(); String data = method.invoke(obj)==null?"":method.invoke(obj).toString();
Cell cell = dataRow.createCell(columnIndex);
if(data!=null&&!"".equals(data)){
if("int".equals(returnType)){
cell.setCellValue(Integer.parseInt(data));
}else if("long".equals(returnType)){
cell.setCellValue(Long.parseLong(data));
}else if("float".equals(returnType)){
cell.setCellValue(floatDecimalFormat.format(Float.parseFloat(data)));
}else if("double".equals(returnType)){
cell.setCellValue(doubleDecimalFormat.format(Double.parseDouble(data)));
}else{
cell.setCellValue(data);
}
}
}else{ //字段为空 检查该列是否是公式
if(colFormula!=null){
String sixBuf = colFormula[columnIndex].replace("@", (rowIndex+1)+"");
Cell cell = dataRow.createCell(columnIndex);
cell.setCellFormula(sixBuf.toString());
}
}
}
} }
} workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 将16进制的颜色代码写入样式中来设置颜色
* @param style 保证style统一
* @param color 颜色:66FFDD
* @param index 索引 8-64 使用时不可重复
* @return
*/
public CellStyle setColor(CellStyle style,String color,short index){
if(color!=""&&color!=null){
//转为RGB码
int r = Integer.parseInt((color.substring(0,2)),16); //转为16进制
int g = Integer.parseInt((color.substring(2,4)),16);
int b = Integer.parseInt((color.substring(4,6)),16);
//自定义cell颜色
HSSFPalette palette = workbook.getCustomPalette();
palette.setColorAtIndex((short)index, (byte) r, (byte) g, (byte) b); style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(index);
}
return style;
} /**
* 设置字体并加外边框
* @param style 样式
* @param style 字体名
* @param style 大小
* @return
*/
public CellStyle setFontAndBorder(CellStyle style,String fontName,short size){
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints(size);
font.setFontName(fontName);
font.setBold(true);
style.setFont(font);
style.setBorderBottom(CellStyle.BORDER_THIN); //下边框
style.setBorderLeft(CellStyle.BORDER_THIN);//左边框
style.setBorderTop(CellStyle.BORDER_THIN);//上边框
style.setBorderRight(CellStyle.BORDER_THIN);//右边框
return style;
}
/**
* 删除文件
* @param fileDir
* @return
*/
public boolean deleteExcel(){
boolean flag = false;
File file = new File(this.fileDir);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
file.delete();
flag = true;
}
}
return flag;
}
/**
* 删除文件
* @param fileDir
* @return
*/
public boolean deleteExcel(String path){
boolean flag = false;
File file = new File(path);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
file.delete();
flag = true;
}
}
return flag;
}
}

poi导出excel表格的更多相关文章

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

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

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

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

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

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

  4. Apache POI导出excel表格

    项目中我们经常用到导出功能,将数据导出以便于审查和统计等.本文主要使用Apache POI实现导出数据. POI中文文档 简介 ApachePOI是Apache软件基金会的开放源码函式库,POI提供A ...

  5. 使用org.apache.poi导出Excel表格

    public HSSFWorkbook MakeExcel(List<TransactionLogVO> logList) { // SimpleDateFormat sdf = new ...

  6. java中使用 POI导出excel表格的简单实现

    大概流程分7步: 1.创建工作簿 --> 2.创建sheet表 --> 3.创建row行(建议使用循环) --> 4.用row行逐一创建单元格(建议使用循环) --> 5.单元 ...

  7. Java之POI导出Excel(一):单sheet

    相信在大部分的web项目中都会有导出导入Excel的需求,今天我们就来看看如何用Java代码去实现 用POI导出Excel表格. 一.pom引用 pom文件中,添加以下依赖 查看代码  <!-- ...

  8. poi导出excel

    Java使用poi组件导出excel报表,能导出excel报表的还可以使用jxl组件,但jxl想对于poi功能有限,jxl应该不能载excel插入浮动层图片,poi能很好的实现输出excel各种功能, ...

  9. apache poi导出excel报表

    Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能.POI为"P ...

随机推荐

  1. [转][Java]Maven使用阿里云镜像

    本文来自:http://www.cnblogs.com/justforcon/p/6792039.html <settings xmlns="http://maven.apache.o ...

  2. springmvc和activemq的整合使用

    1.简介:ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线.ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台 ...

  3. js手机号正则表达式验证

    var phone = $("#phone").val(); //陈旧版 var parphone = /^(((13[0-9]{1})|(17[0-9]{1})|(15[0-9] ...

  4. 支付宝吱口令自动复制脚本,自动复制 JavaScript 代码介绍

    本文转自:http://www.sojson.com/blog/262.html 最近支付宝#吱口令#的信息随处可见,可谓是铺天盖地,群里发这样的信息给被踢了不少.我开始还在鄙视这些人,有几个小钱?然 ...

  5. 阶段性总结(PHP-JSON)

    PHP JSON 本节我们将为大家介绍如何使用 PHP 语言来编码和解码 JSON 对象. 在没有json编码和解码之前,我们 html前台 和 PHP后台 之间的数据传输只能用字符串的方式传输. 但 ...

  6. 如何将字符串去重复demo工具

    //方法一:使用集合的indexOf方法 public static void one(){ String string="aaaaaakkkkkkmnf";//需去重复的字符串s ...

  7. Mysql总结(二)

    数据库.表.字段.行 问:查询姓黄或洪的男生分析:数据从哪来,哪个表stu条件:姓黄或洪name or and 男生gender答:select * from stu where gender=1 a ...

  8. 装linux双系统

    一般的电脑都是一个盘的,只要分个区给linux就行了,好装.大概可以看看这篇:http://jingyan.baidu.com/article/c275f6bacc3326e33c756743.htm ...

  9. GetEnumName 枚举名称 字符串

    System.TypInfo.pas System.TypInfo.hpp http://docwiki.embarcadero.com/Libraries/Tokyo/en/System.TypIn ...

  10. linux命令 环境设置 顺序

    转 http://blog.csdn.net/dingxy/article/details/4016383 在登录Linux时要执行文件的过程如下: 在刚登录Linux时,首先启动 /etc/prof ...