关于poi的导出(POI)

摘要:
非常简单,我可以将打包的POI导出类直接与packagecom.xst一起使用。科蒙;importjava.io。IOException;importjava.io。输出流;导入java.lang.reflect。领域导入java.lang.reflect。方法导入java.text。SimpleDateFormat;导入java

很简单 我封装好的poi导出类 可以拿来直接用

package com.xst.common;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

public class newExcel <T,J>{
public static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator");
public void exportExcel(String title, String[] headers,Collection<?> dataList, Object sumData,OutputStream out, String pattern,int[] width) throws Exception{
exportSumMoneyExcel(title, headers, dataList,sumData,out,pattern,width);
}

@SuppressWarnings("unchecked")
private void exportSumMoneyExcel(String title, String[] headers,Collection<?> dataList, Object sumData,OutputStream out, String pattern,int[] width) throws Exception{
try {
//声明一个工作薄
SXSSFWorkbook workbook=new SXSSFWorkbook(1000);
//生成表格
SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet(title);

for(int i = 0;i < width.length;i++){
sheet.setColumnWidth(i,width[i]*256+184);
}

// 1.标题的样式
CellStyle style = workbook.createCellStyle();
//标题背景色为灰色
//style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
//前置背景色
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
//下边框样式
style.setBorderBottom(CellStyle.BORDER_THIN);
//左边框样式
style.setBorderLeft(CellStyle.BORDER_THIN);
//右边框样式
style.setBorderRight(CellStyle.BORDER_THIN);
//上边框样式
style.setBorderTop(CellStyle.BORDER_THIN);
//设置单元格内容水平居中
style.setAlignment(CellStyle.ALIGN_CENTER);
// 标题的字体样式
Font font = workbook.createFont();//生成字体
//设置字体颜色
font.setColor(IndexedColors.BLACK.index); //设置字体颜色为黑色
//设置字体大小
font.setFontHeightInPoints((short) 12);
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体加粗
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);

// 内容样式
CellStyle style2 = workbook.createCellStyle();
//内容背景色为黄色
style2.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.index);
style2.setFillPattern(CellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(CellStyle.BORDER_THIN);
style2.setBorderLeft(CellStyle.BORDER_THIN);
style2.setBorderRight(CellStyle.BORDER_THIN);
style2.setBorderTop(CellStyle.BORDER_THIN);
style2.setAlignment(CellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 内容字体样式
Font font2 = workbook.createFont();
font2.setColor(IndexedColors.BLACK.index); //设置数据字体为黑色
font2.setBoldweight(Font.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样式
style2.setFont(font2);
// 合计的样式
CellStyle style3 = workbook.createCellStyle();
//内容背景色为白色
style3.setFillForegroundColor(IndexedColors.WHITE.index);
style3.setFillPattern(CellStyle.SOLID_FOREGROUND);
style3.setBorderBottom(CellStyle.BORDER_THIN);
style3.setBorderLeft(CellStyle.BORDER_THIN);
style3.setBorderRight(CellStyle.BORDER_THIN);
style3.setBorderTop(CellStyle.BORDER_THIN);
style3.setAlignment(CellStyle.ALIGN_CENTER);
style3.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 内容字体样式
Font font3 = workbook.createFont();
font3.setColor(IndexedColors.BLUE.index); //设置数据字体为绿色
font3.setBoldweight(Font.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样式
style3.setFont(font3);
// 产生表格标题行
SXSSFRow row = (SXSSFRow) sheet.createRow(0);
//设置行高
row.setHeight((short)20);
//行高的像素数
row.setHeightInPoints(20);
for (short i = 0; i < headers.length; i++) {
SXSSFCell cell=(SXSSFCell) row.createCell(i);
cell.setCellStyle(style);
cell.setCellValue(headers[i]);
}
// 遍历集合数据,产生数据行
Iterator<?> it = dataList.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = (SXSSFRow) sheet.createRow(index);
T t = (T) it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < fields.length; i++) {
SXSSFCell cell=(SXSSFCell) row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
if(value==null){
value=" ";
}
String textValue = null;
if (value instanceof Boolean) {
boolean bValue = (Boolean) value;
textValue = "男";
if (!bValue) {
textValue = "女";
}
} else if (value instanceof Date) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
}else if (value instanceof byte[]) {
/*// 有图片时,设置行高为60px;
row.setHeightInPoints(60);
// 设置图片所在列宽度为80px,注意这里单位的一个换算
sheet.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
1023, 255, (short) 6, index, (short) 6, index);
// anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(
bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));*/
} else {
// 其它数据类型都当作字符串简单处理
textValue = value.toString();
}
// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
if (textValue != null) {
// Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Pattern p = Pattern.compile("^(-?\d+)(\.\d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches() && textValue.length()<12) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
cell.setCellValue(textValue);
}
}

}catch (Exception e) {
e.printStackTrace();
}finally {
// 清理资源
}
}//for
}//while
if (sumData!=null) {
SXSSFSheet sheet2=(SXSSFSheet) workbook.getSheetAt(0); //获取到工作表,因为一个excel可能有多个工作表
SXSSFRow row2=(SXSSFRow)sheet2.getRow(0); //获取第一行(excel中的行默认从0开始,所以这就是为什么,一个excel必须有字段列头),即,字段列头,便于赋值
row2=(SXSSFRow) sheet2.createRow((short)(sheet2.getLastRowNum()+1));
SXSSFCell cell0=(SXSSFCell)row2.createCell(0);
cell0.setCellStyle(style3);
cell0.setCellValue("合计:");
Field[] fields = sumData.getClass().getDeclaredFields();
try {
for (short i = 0; i < fields.length; i++) {
SXSSFCell cell = (SXSSFCell)row2.createCell(i+1);
cell.setCellStyle(style3);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);

Class tCls = sumData.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(sumData, new Object[] {});
if(value==null){
value=" ";
}
String textValue = null;
if (value instanceof Boolean) {
boolean bValue = (Boolean) value;
textValue = "男";
if (!bValue) {
textValue = "女";
}
} else if (value instanceof Date) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
}else if (value instanceof byte[]) {
/*// 有图片时,设置行高为60px;
row.setHeightInPoints(60);
// 设置图片所在列宽度为80px,注意这里单位的一个换算
sheet.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
1023, 255, (short) 6, index, (short) 6, index);
// anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(
bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));*/
} else {
// 其它数据类型都当作字符串简单处理
textValue = value.toString();
}
// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
if (textValue != null) {
// Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Pattern p = Pattern.compile("^(-?\d+)(\.\d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches() && textValue.length()<12) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
cell.setCellValue(textValue);
}
}
}//for
} catch (Exception e) {
e.printStackTrace();
} finally {
// 清理资源
}
}//if
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}//方法
}//类

你们复制好直接用:接下来的代码就是你们每一个controller里面的代码了

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formatDate = sdf.format(date);
String filename= new String((formatDate.replace("-", "") +" 销售物料管理.xls").getBytes(),"iso-8859-1");
response.setContentType("application/octet-stream");
response.setContentType("application/OCTET-STREAM;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="+filename);
response.setContentType("application/msexcel");
String[] headers = { "原料名称","价格(元)"};
int [] width={28,15};
String title = "销售物料管理";
newExcel<Settb109ExtA,Settb109ExtA> excel = new newExcel<Settb109ExtA,Settb109ExtA>();
OutputStream out = response.getOutputStream();
excel.exportExcel(title, headers,settb109selectList, null, out, title, width);
out.close();

中间的样式大家可以上官网上面进行查询和学习 今天我只分享了封装好的poi

免责声明:文章转载自《关于poi的导出(POI)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇android的armeabi和armeabi-v7aDELPHI 解析 JSON下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

XAMPP phpmind Agileone 环境搭建及遇到问题的解决方法

  首先分别介绍下软件的作用: XAMPP:XAMPP(Apache+MySQL+PHP+PERL)是一个功能强大的建站集成软件包。安装 Apache 服务器,然后再配置MySQL、PHP 和 Perl等软件环境,版本和操作方法,一不小心就会导致不兼容;XAMPP 是一个易于安装且包含 MySQL、PHP 和 Perl 的 Apache 发行版,集合多种软...

linux服务器的Gzip文件压缩方法[转]

一、gzip介绍          gzip是GNU zip的缩写,它是一个GNU自由软件的文件压缩程序,也经常用来表示gzip这种文件格式。软件的作者是Jean-loup Gailly和Mark Adler。1992年10月31日第一次公开发布,版本号是0.1,目前的稳定版本是1.2.4。         Gzip主要用于Unix系统的文件压缩。我们在L...

mac 下 apache设置

windows下面的apache配置 apache是mac下是默认就有的,我们只需使用命令开启、暂停和重启就好了 sudo apachectl start sudo apachectl stop sudo apachectl restart 但是这个apache 开启后,默认访问的是 /Library(资源库)/WebServer/Documents/ 目...

apache 访问日志access_log 配置和解析 rotatelogs分割日志

一、解析访问日志        apache 的访问日志记载着大量的信息,学会高效快捷的读出其中关键信息对我们的工作有极大帮助。       如果Apache的安装方式是默认安装,服务器一运行就会有两个日志文件生成。       这两个文件是 access_log(在Windows上是access.log)                        ...

spark parquet 从hdfs 上读 和写 scala 版本

import org.apache.spark.SparkConf import org.apache.spark.SparkContext import org.apache.spark.sql.SQLContext import org.apache.spark.sql.DataFrame import org.apache.spark.sql.Sav...

Eclipse利用Maven快速上手搭建MyBatis

一、what is maven? Maven项目对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的项目管理工具软件。 Maven 除了以程序构建能力为特色之外,还提供高级项目管理工具。由于 Maven 的缺省构建规则有较高的可重用性,所以常常用两三行 Maven 构建脚本就可以构建简单的项目。由于 Maven 的面向项目的方法,许多...