java输出12345_java导入导出excel (仅作为个人学习使用)

importjava.io.IOException;importjava.io.OutputStream;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.util.Collection;importjava.util.Date;importjava.util.Iterator;importjava.util.Map;importjava.util.regex.Matcher;importjava.util.regex.Pattern;importorg.apache.commons.io.IOUtils;importorg.apache.commons.lang3.time.FastDateFormat;importorg.apache.poi.hssf.usermodel.HSSFClientAnchor;importorg.apache.poi.hssf.usermodel.HSSFRichTextString;importorg.apache.poi.ss.usermodel.BorderStyle;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.CellStyle;importorg.apache.poi.ss.usermodel.ClientAnchor;importorg.apache.poi.ss.usermodel.ClientAnchor.AnchorType;importorg.apache.poi.ss.usermodel.Comment;importorg.apache.poi.ss.usermodel.Drawing;importorg.apache.poi.ss.usermodel.FillPatternType;importorg.apache.poi.ss.usermodel.Font;importorg.apache.poi.ss.usermodel.HorizontalAlignment;importorg.apache.poi.ss.usermodel.IndexedColors;importorg.apache.poi.ss.usermodel.RichTextString;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.VerticalAlignment;importorg.apache.poi.ss.usermodel.Workbook;importorg.apache.poi.xssf.streaming.SXSSFWorkbook;importorg.apache.poi.xssf.usermodel.XSSFClientAnchor;importorg.apache.poi.xssf.usermodel.XSSFRichTextString;importorg.springframework.util.StringUtils;/*** 功能说明:导出模板(待重构)

* 典型用法:无

* 特殊用法:无

* 创建者:phil

* 创建时间: 2017年10月13日

* 修改人:phil

* 修改时间:2017年10月18日

* 修改原因: 升级poi3.17 重写 修改内容: 版本号:2.0*/

public class ExportExcel{/***

*@paramsheetTitle

* sheet名称

*@paramheaders

* 列表标题

*@paramdataset

* 内容

*@paramout*/

//public void exportExcel(String sheetTitle, String[] headers, String[]//columns, Collection dataset,//OutputStream out, String datePattern) {//exportExcelByColumn(sheetTitle, headers, columns, dataset, out, datePattern);//}

/*** 导出 xls格式Excel HSSF

*@paramtitle excel表底部标签名

*@paramheaders 列名

*@paramcolumns 列名对应字段

*@paramdataset 导出数据

*@paramout

*@parampattern*/

public void exportHSExcelByColumn(String title, String[] headers, String[] columns, Collectiondataset,

OutputStream out, String pattern) {

Workbook workbook= newSXSSFWorkbook();//生成一个表格

Sheet sheet =workbook.createSheet(title);//设置表格默认列宽度为20个字节

sheet.setDefaultColumnWidth(20);

sheet.setDefaultRowHeightInPoints(24);//生成一个 表格标题行样式

CellStyle style =workbook.createCellStyle();//设置这些样式

style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());

style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

style.setBorderBottom(BorderStyle.THIN);

style.setBorderLeft(BorderStyle.THIN);

style.setBorderRight(BorderStyle.THIN);

style.setBorderTop(BorderStyle.THIN);

style.setAlignment(HorizontalAlignment.CENTER);//生成一个字体

Font font =workbook.createFont();

font.setColor(IndexedColors.WHITE.getIndex());

font.setFontHeightInPoints((short) 12);

font.setBold(true);//font.setBoldweight((short)700));//把字体应用到当前的样式

style.setFont(font);//生成并设置另一个样式 内容的背景

CellStyle style2 =workbook.createCellStyle();

style2.setFillForegroundColor(IndexedColors.WHITE.getIndex());

style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);

style2.setBorderBottom(BorderStyle.THIN);

style2.setBorderLeft(BorderStyle.THIN);

style2.setBorderRight(BorderStyle.THIN);

style2.setBorderTop(BorderStyle.THIN);

style2.setAlignment(HorizontalAlignment.CENTER);

style2.setVerticalAlignment(VerticalAlignment.CENTER);//生成另一个字体

Font font2 =workbook.createFont();

font.setBold(true);//font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//把字体应用到当前的样式

style2.setFont(font2);//声明一个画图的顶级管理器

Drawing> patriarch =sheet.createDrawingPatriarch();//定义注释的大小和位置

Comment comment = patriarch.createCellComment(new HSSFClientAnchor(0, 0, 0,0, (short)4, 2, (short)6, 5));//设置注释内容

comment.setString(new HSSFRichTextString("Created By Phil"));//设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.

comment.setAuthor("phil");//产生表格标题行

Row row = sheet.createRow(0);for (int i = 0; i < headers.length; i++) {

Cell cell=row.createCell(i);

cell.setCellStyle(style);

RichTextString text= newHSSFRichTextString(headers[i]);

cell.setCellValue(text);

}if(StringUtils.isEmpty(pattern)) {

pattern= "yyyy/MM/dd";

}

FastDateFormat instance=FastDateFormat.getInstance(pattern);//遍历集合数据,产生数据行

Iterator it =dataset.iterator();int index = 0;int count = 0;while(it.hasNext()) {

index++;

row=sheet.createRow(index);

T t=(T) it.next();//利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值//Field[] fields = t.getClass().getDeclaredFields();

count = headers.length < columns.length ?headers.length : columns.length;for (int i = 0; i < count; i++) {

Cell cell=row.createCell(i);

cell.setCellStyle(style2);

String fieldName=columns[i];

String getMethodName= "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);try{

Class extends Object> tCls =t.getClass();

Method getMethod= tCls.getMethod(getMethodName, newClass[] {});

Object value= getMethod.invoke(t, newObject[] {});//判断值的类型后进行强制类型转换

String textValue = null;if (value instanceofDate) {

Date date=(Date) value;

textValue=instance.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;

ClientAnchor anchor= new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index);

anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE);

patriarch.createPicture(anchor, workbook.addPicture(bsValue, SXSSFWorkbook.PICTURE_TYPE_JPEG));

}else{//其它数据类型都当作字符串简单处理//if (value != null) {//textValue = value.toString();//if (textValue.equalsIgnoreCase("VLD")) {//textValue = "有效";//} else if (textValue.equalsIgnoreCase("IVD")) {//textValue = "无效";//}//} else {//textValue = "";//}

}//如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成

if (textValue != null) {

Pattern p= Pattern.compile("^//d+(//.//d+)?$");

Matcher matcher=p.matcher(textValue);if(matcher.matches()) {//是数字当作double处理

cell.setCellValue(Double.parseDouble(textValue));

}else{

RichTextString richString= newHSSFRichTextString(textValue);

Font font3=workbook.createFont();

font3.setColor(IndexedColors.BLACK.index);//内容

richString.applyFont(font3);

cell.setCellValue(richString);

}

}

}catch(SecurityException e) {

e.printStackTrace();

}catch(NoSuchMethodException e) {

e.printStackTrace();

}catch(IllegalArgumentException e) {

e.printStackTrace();

}catch(IllegalAccessException e) {

e.printStackTrace();

}catch(InvocationTargetException e) {

e.printStackTrace();

}

}

}try{

workbook.write(out);

}catch(IOException e) {

e.printStackTrace();

}finally{

IOUtils.closeQuietly(workbook);

IOUtils.closeQuietly(out);

}

}/*** 导出 xlsx格式Excel XSSF

*@paramtitle

*@paramheaders

*@paramcolumns

*@paramdataset

*@paramout

*@parampattern*/

public voidexportXSExcelByColumn(String title, String[] headers, String[] columns,

Collection>dataset, OutputStream out, String pattern) {

Workbook workbook= newSXSSFWorkbook();//生成一个表格

Sheet sheet =workbook.createSheet(title);//设置表格默认列宽度为20个字节

sheet.setDefaultColumnWidth(20);

sheet.setDefaultRowHeightInPoints(24);//生成一个 表格标题行样式

CellStyle style =workbook.createCellStyle();//设置这些样式

style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());

style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

style.setBorderBottom(BorderStyle.THIN);

style.setBorderLeft(BorderStyle.THIN);

style.setBorderRight(BorderStyle.THIN);

style.setBorderTop(BorderStyle.THIN);

style.setAlignment(HorizontalAlignment.CENTER);//生成一个字体

Font font =workbook.createFont();

font.setColor(IndexedColors.WHITE.getIndex());

font.setFontHeightInPoints((short) 12);

font.setBold(true);//font.setBoldweight((short)700));//把字体应用到当前的样式

style.setFont(font);//生成并设置另一个样式 内容的背景

CellStyle style2 =workbook.createCellStyle();

style2.setFillForegroundColor(IndexedColors.WHITE.getIndex());

style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);

style2.setBorderBottom(BorderStyle.THIN);

style2.setBorderLeft(BorderStyle.THIN);

style2.setBorderRight(BorderStyle.THIN);

style2.setBorderTop(BorderStyle.THIN);

style2.setAlignment(HorizontalAlignment.CENTER);

style2.setVerticalAlignment(VerticalAlignment.CENTER);//生成另一个字体

Font font2 =workbook.createFont();

font.setBold(true);//font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//把字体应用到当前的样式

style2.setFont(font2);//声明一个画图的顶级管理器

Drawing> patriarch =sheet.createDrawingPatriarch();//定义注释的大小和位置

Comment comment = patriarch.createCellComment(new XSSFClientAnchor(0, 0, 0,0, (short)4, 2, (short)6, 5));//设置注释内容

comment.setString(new XSSFRichTextString("Created By Phil"));//设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.

comment.setAuthor("phil");//产生表格标题行

Row row = sheet.createRow(0);for (int i = 0; i < headers.length; i++) {

Cell cell=row.createCell(i);

cell.setCellStyle(style);

RichTextString text= newXSSFRichTextString(headers[i]);

cell.setCellValue(text);

}if(StringUtils.isEmpty(pattern)) {

pattern= "yyyy/MM/dd";

}

FastDateFormat instance=FastDateFormat.getInstance(pattern);//遍历集合数据,产生数据行

Iterator> it = dataset.iterator(); //多个Map集合

int index = 0;int count = 0;while(it.hasNext()) {

index++;

row=sheet.createRow(index);

Map map =it.next();

count= headers.length < columns.length ?headers.length : columns.length;for (int i = 0; i < count; i++) {

Cell cell=row.createCell(i);

cell.setCellStyle(style2);try{

Object value=map.get(columns[i]);//判断值的类型后进行强制类型转换

String textValue = null;if (value instanceofDate) {

Date date=(Date) value;

textValue=instance.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;

ClientAnchor anchor= new XSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index);

anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE);

patriarch.createPicture(anchor, workbook.addPicture(bsValue, Workbook.PICTURE_TYPE_JPEG));

}else{//其它数据类型都当作字符串简单处理

if (value != null) {

textValue=value.toString();//if (textValue.equalsIgnoreCase("VLD")) {//textValue = "有效";//} else if (textValue.equalsIgnoreCase("IVD")) {//textValue = "无效";//}

} else{

textValue= "";

}

}//如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成

if (textValue != null) {

Pattern p= Pattern.compile("^//d+(//.//d+)?$");

Matcher matcher=p.matcher(textValue);if(matcher.matches()) {//是数字当作double处理

cell.setCellValue(Double.parseDouble(textValue));

}else{

RichTextString richString= newXSSFRichTextString(textValue);

Font font3=workbook.createFont();

font3.setColor(IndexedColors.BLACK.index);//内容

richString.applyFont(font3);

cell.setCellValue(richString);

}

}

}catch(SecurityException e) {

e.printStackTrace();

}

}

}try{

workbook.write(out);

}catch(IOException e) {

e.printStackTrace();

}finally{

IOUtils.closeQuietly(workbook);

IOUtils.closeQuietly(out);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值