1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java支持xls格式的excel导入和导出

java支持xls格式的excel导入和导出

时间:2020-03-18 04:46:13

相关推荐

java支持xls格式的excel导入和导出

第一步:

public static Map<Integer, Map<Integer, String>> importReportExcel(String excelTemplatePath, int index) {

File file = new File(excelTemplatePath);

Map<Integer, Map<Integer, String>> mapRow = new HashMap<Integer, Map<Integer, String>>();

try {

HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));

Sheet sheet = workbook.getSheetAt(index);

for (Row row : sheet) {

Map<Integer, String> mapColumn = new HashMap<Integer, String>();

for (Cell cell : row) {

int type = cell.getCellType();

String cellContext = "";

switch (type) { // 判断数据类型

case Cell.CELL_TYPE_BLANK:// 空的

cellContext = "";

break;

case Cell.CELL_TYPE_BOOLEAN:// 布尔

cellContext = cell.getBooleanCellValue() + "";

break;

case Cell.CELL_TYPE_ERROR:// 错误

cellContext = cell.getErrorCellValue() + "";

break;

case Cell.CELL_TYPE_FORMULA:// 公式

cellContext = cell.getCellFormula();

break;

case Cell.CELL_TYPE_NUMERIC:// 数字或日期

if (HSSFDateUtil.isCellDateFormatted(cell)) {

cellContext = new DataFormatter().formatRawCellContents(cell.getNumericCellValue(), 0, "yyyy-mm-dd");// 格式化日期

} else {

NumberFormat nf = NumberFormat.getInstance();

nf.setGroupingUsed(false);

cellContext = nf.format(cell.getNumericCellValue());

}

break;

case Cell.CELL_TYPE_STRING:// 字符串

cellContext = cell.getStringCellValue();

break;

default:

break;

}

mapColumn.put(cell.getColumnIndex(), cellContext);

}

mapRow.put(row.getRowNum(), mapColumn);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return mapRow;

}

package com.blog.controller.wx.test;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Date;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

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

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.hssf.usermodel.HSSFClientAnchor;

import org.apache.poi.hssf.usermodel.HSSFComment;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;

import org.apache.poi.hssf.usermodel.HSSFFont;

import org.apache.poi.hssf.usermodel.HSSFPatriarch;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;

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

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.hssf.util.HSSFColor;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.Font;

import org.apache.poi.ss.util.CellRangeAddress;

import com.hna.billbao.util.DateUtils;

import com.hna.billbao.util.FileUtils;

import com.hna.billbao.util.TextUtils;

import com.hna.billbao.util.annotation.type.ExcelColumnName;

/**

* 利用开源组件POI3.0.2动态导出EXCEL文档

* @author 微笑风采

* @version v1.0

* @param <T>

*应用泛型,代表任意一个符合javabean风格的类

*注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()

*byte[]表jpg格式的图片数据

*/

public class ExcelUtils<T> {

private static Logger logger = Logger.getLogger(ExcelUtils.class);

/** 应用名称 **/

public static String APP_NAME = "营销平台";

/**

* 导出Excel通用方法

* <b>调用方式:</b>

* <p><pre>

* 1.首先需要声明Head头数组,将会作为Excel的列头:

* String[] headers = { "用户ID", "手机号码", "电子邮箱", "注册日期" ,"账户状态(0:未激活,1:正常)"};<br>

* 2.然后声明Fields数组,数组元素为对象的属性名称:

* String[] fields = {"uid","phone","email","reg_time","is_active"};<br>

* 3.调用以下方法即可:

* exportExcel(request,response,"我是文件名称", userList, headers , fields);

* </pre></p>

* @param response

* @param request

* @param fileName 导出的文件名称

* @param downList 导出的对象集合

* @param headers Excel的列头

* @param fields 对象Fields数组

* @return 导出成功返回true,否则返回false

* @throws Exception

*/

public static <T> boolean exportExcel(HttpServletRequest request,HttpServletResponse response,String fileName,List<T> downList,String headerName,String[] headers,String[] fields) throws Exception{

ExcelUtils<T> ex = new ExcelUtils<T>();

String dicpath = System.getProperty("root")+"/data/exportxls";

File dicfile = new File(dicpath);

if(!dicfile.exists()){

dicfile.mkdirs();

}

String path = System.getProperty("root")+"/data/exportxls/"+fileName+".xls";

File file = new File(path);

if(!file.exists()){

file.createNewFile();

}

OutputStream out = new FileOutputStream(path);

//List中对象为Map

if(downList.size()>0 && downList.get(0) instanceof Map){

ex.exportExcel(downList,out,fileName,headerName,fields,headers);

}else{

ex.exportExcel(headers, downList, out,fileName,fields);

}

FileUtils.download(request,response,path);//下载操作

return true;

}

/**

* 导出Excel通用方法

* <b>调用方式:</b>

* <p><pre>

* 1.首先需要声明Head头数组,将会作为Excel的列头:

* String[] headers = { "用户ID", "手机号码", "电子邮箱", "注册日期" ,"账户状态(0:未激活,1:正常)"};<br>

* 2.然后声明Fields数组,数组元素为对象的属性名称:

* String[] fields = {"uid","phone","email","reg_time","is_active"};<br>

* 3.调用以下方法即可:

* exportExcel(request,response,"我是文件名称", userList, headers , fields);

* </pre></p>

* @param response

* @param request

* @param fileName 导出的文件名称

* @param downList 导出的对象集合

* @param headers Excel的列头

* @param fields 对象Fields数组

* @return 导出成功返回true,否则返回false

*/

public static <T> boolean exportExcel(HttpServletRequest request,HttpServletResponse response,String fileName,List<T> downList,String[] headers,String[] fields){

try {

ExcelUtils<T> ex = new ExcelUtils<T>();

//String dicpath = System.getProperty("root")+"/data/exportxls";

String dicpath ="/data/exportxls";

File dicfile = new File(dicpath);

if(!dicfile.exists()){

dicfile.mkdirs();

}

String path = fileName+".xls";

File file = new File(path);

if(!file.exists()){

file.createNewFile();

}

OutputStream out = new FileOutputStream(path);

//List中对象为Map

if(downList.size()>0 && downList.get(0) instanceof Map){

ex.exportExcel(downList,out,fileName,fields,headers);

}else{

ex.exportExcel(headers, downList, out,fileName,fields);

}

FileUtils.download(request,response,path);//下载操作

return true;

} catch (Exception e) {

e.printStackTrace();

logger.error("导出Excel异常:",e);

return false;

}

}

public void exportExcel(String[] headers, Collection<T> dataset,

OutputStream out,String fileName, String[] fields) throws Exception {

exportExcel(fileName, headers, dataset, out, "yyyy-MM-dd", fields);

}

/**

* 为导出HashMap使用

* @param downList

* @param out

* @throws Exception

*/

public void exportExcel(List<T> downList,

OutputStream out,String fileName,String headerName,String[] fields,String[] heads) throws Exception {

exportExcel(fileName, downList, out, "yyyy-MM-dd",headerName,fields,heads);

}

/**

* 为导出HashMap使用

* @param downList

* @param out

* @throws Exception

*/

public void exportExcel(List<T> downList,

OutputStream out,String fileName,String[] fields,String[] heads) throws Exception {

exportExcel(fileName, downList, out, "yyyy-MM-dd",fields,heads);

}

/**

* 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上

*

* @param title

*表格标题名

* @param headers

*表格属性列名数组

* @param dataset

*需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的

*javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)

* @param out

*与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中

* @param pattern

*如果有时间数据,设定输出格式。默认为"yyy-MM-dd"

*

* @param fields

*要进行显示的字段

* @throws Exception

*/

@SuppressWarnings("unchecked")

public void exportExcel(String title, String[] headers,

Collection<T> dataset, OutputStream out, String pattern,

String[] fields) throws Exception {

// 声明一个工作薄

HSSFWorkbook workbook = new HSSFWorkbook();

// 生成一个表格

HSSFSheet sheet = workbook.createSheet(title);

// 设置表格默认列宽度为15个字节

sheet.setDefaultColumnWidth((short) 25);

sheet.setDefaultRowHeight((short)(20*20));

// 生成一个样式

HSSFCellStyle style = workbook.createCellStyle();

// 设置这些样式

style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);

style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

style.setBorderBottom(HSSFCellStyle.BORDER_THIN);

style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

style.setBorderRight(HSSFCellStyle.BORDER_THIN);

style.setBorderTop(HSSFCellStyle.BORDER_THIN);

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

// 生成一个字体

HSSFFont font = workbook.createFont();

font.setColor(HSSFColor.VIOLET.index);

font.setFontHeightInPoints((short) 12);

font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

// 把字体应用到当前的样式

style.setFont(font);

// 生成并设置另一个样式

HSSFCellStyle style2 = workbook.createCellStyle();

style2.setFillForegroundColor(HSSFColor.WHITE.index);

style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);

style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);

style2.setBorderRight(HSSFCellStyle.BORDER_THIN);

style2.setBorderTop(HSSFCellStyle.BORDER_THIN);

style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);

style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

// 生成另一个字体

HSSFFont font2 = workbook.createFont();

font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

font2.setColor(HSSFColor.GREY_80_PERCENT.index);

// 把字体应用到当前的样式

style2.setFont(font2);

// 声明一个画图的顶级管理器

HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

// 定义注释的大小和位置,详见文档

HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,

0, 0, 0, (short) 4, 2, (short) 6, 5));

// 设置注释内容

comment.setString(new HSSFRichTextString(APP_NAME+"系统生成Excel文档"+DateUtils.getTimeNows()));

// 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.

comment.setAuthor("");

// 产生表格标题行

HSSFRow row = sheet.createRow(0); // 标记 !!@@@

for (short i = 0; i < headers.length; i++) {

HSSFCell cell = row.createCell(i);

cell.setCellStyle(style);

HSSFRichTextString text = new HSSFRichTextString(headers[i]);

cell.setCellValue(text);

}

// 遍历集合数据,产生数据行

Iterator<T> it = dataset.iterator();

int index = 0;

while (it.hasNext()) {

index++;

row = sheet.createRow(index);

T t = (T) it.next();

// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值

for (short i = 0; i < fields.length; i++) {

String fieldName = fields[i];

HSSFCell cell = row.createCell(i);

cell.setCellStyle(style2);

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[] {});

// 判断值的类型后进行强制类型转换

String textValue = null;

if (value != 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[]) {

try {

// 有图片时,设置行高为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));

} catch (Exception e) {

continue;

}

} else {

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

textValue = value.toString();

}

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

if (textValue != null) {

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

Matcher matcher = p.matcher(textValue);

if (matcher.matches()) {

// 是数字当作double处理

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

} else {

HSSFRichTextString richString = new HSSFRichTextString(textValue);

HSSFFont font3 = workbook.createFont();

font3.setColor(HSSFColor.BLUE.index);

richString.applyFont(font3);

cell.setCellValue(richString);

}

}

}

} catch (Exception e) {

e.printStackTrace();

} finally {

// 清理资源

}

}

}

try {

workbook.write(out);

} catch (IOException e) {

throw new Exception(e.getMessage(), e);

}

}

/**

* 导出Excel数据,需要的是List<HashMap<String, Object>>数据

* @param headerName : 表头名

* @param title

* @param dataset

* @param out

* @param pattern

* @throws Exception

*/

public void exportExcel(String title,List<T> datalist, OutputStream out, String pattern,String headerName,String[] fields,String[] heads) throws Exception {

List<HashMap<String, Object>> dataset = (List<HashMap<String, Object>>) datalist;

// 声明一个工作薄

HSSFWorkbook workbook = new HSSFWorkbook();

// 生成一个表格

HSSFSheet sheet = workbook.createSheet(title);

// 设置表格默认列宽度为15个字节

sheet.setDefaultColumnWidth((short) 25);

sheet.setDefaultRowHeight((short)(20*20));

// 生成一个样式

HSSFCellStyle style = workbook.createCellStyle();

// 设置这些样式

style.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);

style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

style.setBorderBottom(HSSFCellStyle.BORDER_THIN);

style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

style.setBorderRight(HSSFCellStyle.BORDER_THIN);

style.setBorderTop(HSSFCellStyle.BORDER_THIN);

style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐

style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐

// 生成一个字体

HSSFFont font = workbook.createFont();

font.setColor(HSSFColor.VIOLET.index);

font.setFontHeightInPoints((short) 12);

font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

// 把字体应用到当前的样式

style.setFont(font);

// 生成并设置另一个样式

HSSFCellStyle style2 = workbook.createCellStyle();

style2.setFillForegroundColor(HSSFColor.WHITE.index);

style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);

style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);

style2.setBorderRight(HSSFCellStyle.BORDER_THIN);

style2.setBorderTop(HSSFCellStyle.BORDER_THIN);

style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);

style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

// 生成另一个字体

HSSFFont font2 = workbook.createFont();

font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

font2.setColor(HSSFColor.BLUE_GREY.index);

// 把字体应用到当前的样式

style2.setFont(font2);

// 声明一个画图的顶级管理器

HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

// 定义注释的大小和位置,详见文档

HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,

0, 0, 0, (short) 4, 2, (short) 6, 5));

// 设置注释内容

comment.setString(new HSSFRichTextString(APP_NAME+"系统生成Excel文档"+DateUtils.getTimeNows()));

// 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.

comment.setAuthor("");

// ----- 合并单元格

HSSFRow headerRow = sheet.createRow(0);

headerRow.setHeightInPoints(50); // --

HSSFCell headercell = headerRow.createCell(0);

headercell.setCellValue(headerName);

CellStyle headerStyle;

Font titleFont = workbook.createFont();

titleFont.setFontHeightInPoints((short)20); // 大小

// titleFont.setColor(IndexedColors.DARK_BLUE.getIndex()); // 设置字体颜色

headerStyle = workbook.createCellStyle();

headerStyle.setAlignment(CellStyle.ALIGN_CENTER); // 左右居中

headerStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); // 上下居中

headerStyle.setFont(titleFont);

headercell.setCellStyle(headerStyle);

sheet.addMergedRegion(new CellRangeAddress(

0, // 第一行(从0开始)

0, // 最后一行(基于0)

0, // 第一列(从0开始)

heads.length - 1 // 最后一列(从0开始)

));

// 产生表格标题行

HSSFRow row = sheet.createRow(1);

short t = 0;

for (String tit : heads) {

HSSFCell cell = row.createCell(t);

cell.setCellStyle(style);

HSSFRichTextString text = new HSSFRichTextString(tit);

cell.setCellValue(text);

t++;

}

int index = 1;

// 遍历集合数据,产生数据行

for (HashMap<String, Object> data : dataset) {

short i = 0;

index++;

row = sheet.createRow(index);

for (String key : fields) {

HSSFCell cell = row.createCell(i);

cell.setCellStyle(style2);

Object value = data.get(key);

// 判断值的类型后进行强制类型转换

String textValue = null;

if (value != null) {

textValue = value.toString();

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

if (textValue != null) {

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

Matcher matcher = p.matcher(textValue);

if (matcher.matches()) {

// 是数字当作double处理

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

} else {

HSSFRichTextString richString = new HSSFRichTextString(

textValue);

HSSFFont font3 = workbook.createFont();

font3.setColor(HSSFColor.BLUE.index);

richString.applyFont(font3);

cell.setCellValue(richString);

}

}

}

i++;

}

}

try {

workbook.write(out);

} catch (IOException e) {

throw new Exception(e.getMessage(), e);

}

}

/**

* 导出Excel数据,需要的是List<HashMap<String, Object>>数据

* @param title

* @param dataset

* @param out

* @param pattern

* @throws Exception

*/

public void exportExcel(String title,List<T> datalist, OutputStream out, String pattern,String[] fields,String[] heads) throws Exception {

List<HashMap<String, Object>> dataset = (List<HashMap<String, Object>>) datalist;

// 声明一个工作薄

HSSFWorkbook workbook = new HSSFWorkbook();

// 生成一个表格

HSSFSheet sheet = workbook.createSheet(title);

// 设置表格默认列宽度为15个字节

sheet.setDefaultColumnWidth((short) 25);

sheet.setDefaultRowHeight((short)(20*20));

// 生成一个样式

HSSFCellStyle style = workbook.createCellStyle();

// 设置这些样式

style.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);

style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

style.setBorderBottom(HSSFCellStyle.BORDER_THIN);

style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

style.setBorderRight(HSSFCellStyle.BORDER_THIN);

style.setBorderTop(HSSFCellStyle.BORDER_THIN);

style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐

style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐

// 生成一个字体

HSSFFont font = workbook.createFont();

font.setColor(HSSFColor.VIOLET.index);

font.setFontHeightInPoints((short) 12);

font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

// 把字体应用到当前的样式

style.setFont(font);

// 生成并设置另一个样式

HSSFCellStyle style2 = workbook.createCellStyle();

style2.setFillForegroundColor(HSSFColor.WHITE.index);

style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);

style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);

style2.setBorderRight(HSSFCellStyle.BORDER_THIN);

style2.setBorderTop(HSSFCellStyle.BORDER_THIN);

style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);

style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

// 生成另一个字体

HSSFFont font2 = workbook.createFont();

font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

font2.setColor(HSSFColor.BLUE_GREY.index);

// 把字体应用到当前的样式

style2.setFont(font2);

// 声明一个画图的顶级管理器

HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

// 定义注释的大小和位置,详见文档

HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,

0, 0, 0, (short) 4, 2, (short) 6, 5));

// 设置注释内容

comment.setString(new HSSFRichTextString(APP_NAME+"系统生成Excel文档"+DateUtils.getTimeNows()));

// 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.

comment.setAuthor("");

// 产生表格标题行

HSSFRow row = sheet.createRow(0);

short t = 0;

for (String tit : heads) {

HSSFCell cell = row.createCell(t);

cell.setCellStyle(style);

HSSFRichTextString text = new HSSFRichTextString(tit);

cell.setCellValue(text);

t++;

}

int index = 0;

// 遍历集合数据,产生数据行

for (HashMap<String, Object> data : dataset) {

short i = 0;

index++;

row = sheet.createRow(index);

for (String key : fields) {

HSSFCell cell = row.createCell(i);

cell.setCellStyle(style2);

Object value = data.get(key);

// 判断值的类型后进行强制类型转换

String textValue = null;

if (value != null) {

textValue = value.toString();

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

if (textValue != null) {

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

Matcher matcher = p.matcher(textValue);

if (matcher.matches()) {

// 是数字当作double处理

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

} else {

HSSFRichTextString richString = new HSSFRichTextString(

textValue);

HSSFFont font3 = workbook.createFont();

font3.setColor(HSSFColor.BLUE.index);

richString.applyFont(font3);

cell.setCellValue(richString);

}

}

}

i++;

}

}

try {

workbook.write(out);

} catch (IOException e) {

throw new Exception(e.getMessage(), e);

}

}

/**

* 数据在excel的第一页,excel的第一行为备注使用的,第二行为列名,且与Class里面的列名保持一致。第三行开始为待解析的数据

*

* @param file

*文件名

* @param clazz

*类名

* @param fields

*要显示的属性

* @return

* @throws IOException

*/

public static <T> List<T> readExcelToObject(File file, Class<T> clazz,

String[] fields) throws Exception {

List<T> list = new ArrayList<T>();

POIFSFileSystem fs = null;

HSSFWorkbook wb = null;

try {

FileInputStream fis = new FileInputStream(file);

fs = new POIFSFileSystem(fis);

wb = new HSSFWorkbook(fs);

Map<String, Field> fieldMap = getExcelFields(clazz,fields);

Map<String, Object> item = null;

HSSFSheet sheet = wb.getSheetAt(0);

// 取得各属性对应的位置

HSSFRow row = sheet.getRow(0);

int rowNum = sheet.getLastRowNum();

for (int i = 1; i <= rowNum; i++) {

row = sheet.getRow(i);

if(null==row){

//如果为空,则进行下一行读取

continue;

}

item = new HashMap<String, Object>();

for (int k = 0; k < fields.length; k++) {

// logger.debug("LastCellNum = "+row.getLastCellNum());

// logger.debug("RowNum = "+row.getRowNum());

HSSFCell cell = row.getCell(k);

item.put(fields[k], getCellValue(cell));

}

// 将MAP转化为对象

T itemobj = clazz.newInstance();

for (String needfield : fields) {

Field field = fieldMap.get(needfield);

// System.err.println(needfield+" = "+item.get(needfield));

String value = String.valueOf(item.get(needfield));

// System.err.println("value = "+value);

// logger.debug("value = "+value);

field.setAccessible(true);

if (value != null && !"".equals(value) && !"null".equals(value)) {

if (field.getType() == int.class) {

field.set(itemobj, Integer.valueOf(value));

} else if (field.getType() == String.class) {

field.set(itemobj, value);

} else if (field.getType() == Long.class) {

field.set(itemobj, Date.parse(value));//将时间类型转换为long类型

// field.set(itemobj, Long.valueOf(value));

} else if (field.getType() == boolean.class) {

field.set(itemobj, Boolean.valueOf(value));

// field.set(itemobj, Float.valueOf(value));

} else if (field.getType() == double.class) {

field.set(itemobj, Double.valueOf(value));

} else if (field.getType() == Date.class) {

field.set(itemobj, Date.parse(value));

} else if (field.getType() == byte.class) {

field.set(itemobj, Byte.valueOf(value));

}

}

}

list.add(itemobj);

}

fis.close();

} catch (FileNotFoundException e) {

throw new FileNotFoundException("文件不存在");

} catch (IOException e) {

throw new IOException("文件无法操作",e);

} catch (Exception e) {

e.printStackTrace();

throw new Exception(e.getMessage(), e);

}

return list;

}

/**

* 获取某个单元格的值,并做一定的类型判断。

* @param cell

* @return

*/

public static Object getCellValue(HSSFCell cell) {

Object value = null;

if (cell != null) {

int cellType = cell.getCellType();

HSSFCellStyle style = cell.getCellStyle();

short format = style.getDataFormat();

switch (cellType) {

case HSSFCell.CELL_TYPE_NUMERIC:

DecimalFormat df = new DecimalFormat("#");//将1.700001234E10转换成整型的字符串

double numTxt = Double.parseDouble(df.format(cell.getNumericCellValue()));

if (format == 22 || format == 14){

value = HSSFDateUtil.getJavaDate(numTxt);

if (format == 22) {

value = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());

}

}else{

if (df.format(cell.getNumericCellValue()).length()==11) {

value = df.format(cell.getNumericCellValue());

}else{

value =TextUtils.formatNumber( new DecimalFormat("#.##").format(cell.getNumericCellValue()), 2) ;

}

}

break;

case HSSFCell.CELL_TYPE_BOOLEAN:

boolean booleanTxt = cell.getBooleanCellValue();

value = booleanTxt;

break;

case HSSFCell.CELL_TYPE_BLANK:

value = null;

break;

case HSSFCell.CELL_TYPE_STRING:

HSSFRichTextString rtxt = cell.getRichStringCellValue();

if (rtxt == null) {

break;

}

String txt = rtxt.getString();

value = txt;

break;

default:

// System.out.println(cell.getColumnIndex()+" col cellType="+cellType);

}

}

return value;

}

/**

* 得到Excel列名和字段的对应关系

* @param clazz

* @param fieldNames

* @return

*/

public static Map<String, Field> getExcelFields(Class<?> clazz,String[] fieldNames){

Map<String, Field> fieldMap = new HashMap<String, Field>();

Field[] fields = clazz.getDeclaredFields();

for (Field field : fields) {

ExcelColumnName columnName = field.getAnnotation(ExcelColumnName.class);

if(columnName != null){

fieldMap.put(columnName.value(), field);

}

}

return fieldMap;

}

}

最后一步调用:

String path = "D:\\main\\test.xls";

Map map = ExcelHelperTest.importReportExcel(path, 0);

List<Map> lists = new ArrayList();

for (int i = 0; i < map.size(); i++) {

Map maps = (Map) map.get(i);

lists.add(maps);

System.out.println(maps);

}

for (int i = 0; i < lists.size(); i++) {

Map maps = lists.get(i);

System.out.println("-------------------------->" + maps.get(0));

String acct_id = maps.get(0) + "";

List<Map<String, Bean>> maps2 = service.importList(acct_id);

if (maps2 != null) {

String fileName = "test1";

String[] headers = new String[] { "acct_id", "话费宝用户手机号", "小金库总金额", "小金库总收入", "客户名", "小金库充值订单号",

"小金库充值金额", "充值后账户余额", "充值号码", "充值订单金额", "充值时间" };

String[] fields = new String[] { "acct_id", "phone", "total_amount", "totalin", "cust_name", "ord_id",

"tran_amount", "tran_afteramount", "chargePhone", "chargeAmount", "create_time" };

List<Map> list = new ArrayList<Map>();

String file = null;

for (int j = 0; j < maps2.size(); j++) {

Map maps3 = maps2.get(j);

file = "D:\\main\\" + maps3.get("phone") + "_" + maps3.get("acct_id") + ".xls";

list.add(maps3);

}

logger.info("-------------------------->" + list.size());

FileOutputStream out;

ExcelUtils<Map> excel = new ExcelUtils<Map>();

try {

out = new FileOutputStream(file);

excel.exportExcel(list, out, fileName, fields, headers);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

}

}

这样是我根据导入大量的acct_id而导出相应的每个acct_id数据excel,速度会比较慢。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。